<?php  
//whether ip is from share internet  
if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))     
  {  
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];  
  }  
//whether ip is from proxy  
elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))    
  {  
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];  
  }  
//whether ip is from remote address  
else  
  {  
    $ip_address = $_SERVER['REMOTE_ADDR'];  
  }  
echo $ip_address;  
?>
< ?php  
session_register($name_your_session_here);  
?> 

The following code can be used for it,

header("Location:page_to_redirect.php");
exit();

echo $_COOKIE ["cookie_name"];

preg_split — Split string by a regular expression

< ?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>

explode — Split a string by string
< ?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>
$arr = array('apple', 'grape', 'lemon');

$host = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($host, $username, $password);
//connect to server
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

$host = "localhost";
$username = "root";
$password = "";
 $conn = new PDO("mysql:host=$host;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
unset($_SESSION['object']); 
$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); 
$result = mysql_fetch_array($my_qry);
echo $result['First_name'];
$file="full_path/filename.php"
unlink($file); //make sure you have enough permission to do delete the file.
$string="cakephp and zend";
echo strtoupper($string); 
$string="CAKEPHP AND ZEND";
echo strtolower($string);
$string="cakephp and zend";
echo ucwords($string); 

array_merge example

$array1 = array('one','two');
$array2 = array(1,2);
$result = array_merge($array1,$array2);
print_r($result);

array_combine example

$array1 = array('one','two');
$array2 = array(1,2);
$result = array_combine($array1,$array2);
print_r($result);
$array = array('cakephp','zend');
sizeof($array);
count($array); 

It is used to display the data-type and values of variable. For Example.

$name='WTEN';
var_dump($name);

It will convert an object to array.

$obj = new stdClass();
$obj->key1 ='Value1';
$obj->key2 ='Value3';
$obj->key3 ='Value3';
$obj->key4 ='Value4';
$array = (Array)$obj;
print_r($array);//Array ( [key1] => Value1 [key2] => Value3 [key3] => Value3 [key4] => Value4 ) /pre>
						

file_exists is used to check directory exist OR NOT.
mkdir is used to create the new directory.

$path="/path/to/dir";
if (!file_exists($path)) {
    mkdir($path, 0755, true);
}

func_num_args () used to get the number of arguments passed to the function .

array_flip exchange the keys with their associated values in array ie. Keys becomes values and values becomes keys.

<?php
$arrayName    = array("course1"=>"php","course2"=>"html");

$new_array    =  array_flip($arrayName);
print_r($new_array);
?>
OUTPUT :
Array (
[php] => course1
[html] => course2)
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
 
print_r($result);
 ?>

List() function is used to assign values to a list of variable in one operation and list only works on numerical arrays.

<?php
$varArray = array("PHP","MYsql","Jquery");
list($a, $b, $c) = $varArray;
echo  "I have knowledge of $a,$b and $c.";  
?>

OUTPUT : I have knowledge of PHP,MYsql and Jquery.
 <?php
if (version_compare(PHP_VERSION, '6.0.0') >= 0) {
echo 'I am at least PHP version 6.0.0, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
echo 'I am using PHP 5, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '<')) {
echo 'I am using PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>
<?php
$file = basename($_SERVER['PHP_SELF']); 
$no_of_lines = count(file($file)); 
echo "There are $no_of_lines lines in $file"."\n";
?>
<?php
// current time
  echo date('h:i:s') . "\n";
  // sleep for 5 seconds
  sleep(5);
  // wake up
  echo date('h:i:s')."\n";
?>
<?php
function trinary_Test($n){
$r = $n > 30
? "greater than 30"
: ($n > 20
? "greater than 20"
: ($n >10
? "greater than 10"
: "Input a number atleast greater than 10!")); 
echo $n." : ".$r."\n";
}
trinary_Test(32);
trinary_Test(21);
trinary_Test(12);
trinary_Test(4);
?>
<?php  
$full_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";  
  echo $full_url."\n";  
?>
<?php
 echo php_uname()."\n";
echo PHP_OS."\n";
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo 'This is a server using Windows!';
} else {
echo 'This is a server not using Windows!'."\n";
}
?>
<!DOCTYPE html>  
<html>  
<head>  
<title>My credits page  
</head>  
<body>  
<?php  
// some code of your own  
phpcredits(CREDITS_ALL - CREDITS_FULLPAGE);  
// some more code  
?>  
</body>  
 
<?php
// Create a temporary file in the temporary 
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');
echo $temp_file."\n";
?>
<?php
$ceu = array( "Italy"=>"Rome", "Luxembourg"=>"Luxembourg", "Belgium"=> "Brussels",
"Denmark"=>"Copenhagen", "Finland"=>"Helsinki", "France" => "Paris", "Slovakia"=>"Bratislava",
"Slovenia"=>"Ljubljana", "Germany" => "Berlin", "Greece" => "Athens", "Ireland"=>"Dublin",
"Netherlands"=>"Amsterdam", "Portugal"=>"Lisbon", "Spain"=>"Madrid", "Sweden"=>"Stockholm",
"United Kingdom"=>"London", "Cyprus"=>"Nicosia", "Lithuania"=>"Vilnius", "Czech Republic"=>"Prague", "Estonia"=>"Tallin", "Hungary"=>"Budapest", "Latvia"=>"Riga", "Malta"=> "Valetta","Austria" => "Vienna", "Poland"=>"Warsaw") ;

$max_key = max( array_keys( $ceu) ); 
echo $max_key."\n";
?>
							
<?php
$target_days = mktime(0,0,0,12,31,2013);// modify the birth day 12/31/2013
$today = time();
$diff_days = ($target_days - $today);
$days = (int)($diff_days/86400);
print "Days till next birthday: $days days!"."\n";
?> 

Sample dates : 1996-01-28, 2016-01-28

Expected Result :20 years, 0 months, 5 days

<?php
$sdate = "1996-01-28";
$edate = "2016-01-28";

$date_diff = abs(strtotime($edate) - strtotime($sdate));

$years = floor($date_diff / (365*60*60*24));
$months = floor(($date_diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($date_diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days", $years, $months, $days);
?>
<?php
$dt = "2017-02-23";
echo 'First day : '. date("Y-m-01", strtotime($dt)).' - Last day : '. date("Y-m-t", strtotime($dt))."\n";
?>
<?php
echo date('l \t\h\e jS')."\n";
?> 

Sample seconds : 200000
Expected output : 2 days, 7 hours, 33 minutes and 20 second

<?php
function convert_seconds($seconds) 
 {
  $dt1 = new DateTime("@0");
  $dt2 = new DateTime("@$seconds");
  return $dt1->diff($dt2)->format('%a days, %h hours, %i minutes and %s seconds');
  }
echo convert_seconds(200000)."\n";
?>
<?php
function factorial_of_a_number($n)
{
  if($n ==0)
    {
	   return 1;
    }
  else 
    {	
	   return $n * factorial_of_a_number($n-1);
    }
	}
print_r(factorial_of_a_number(6)."\n");
?>
<?php
function array_sort($a)
{
 for($x=0;$x< count($a);++$x)
  {
    $min = $x;
  for($y=$x+1;$y< count($a);++$y)
   {
	 if($a[$y] < $a[$min] ) 
	 {
	   $temp = $a[$min];
	   $a[$min] = $a[$y];
	   $a[$y] = $temp;
	 }
	}
  }
 return $a;
 }
$a = array(51,14,1,21,'hj');
print_r(array_sort($a));
?>
<?php
//all uppercase letters
print(strtoupper("the quick brown fox jumps over the lazy dog."))."\n";
//all lowercase letters
print(strtolower("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"))."\n";
// make a string's first character uppercase
print(ucfirst("the quick brown fox jumps over the lazy dog."))."\n";
// make a string's first character of all the words uppercase
print(ucwords("the quick brown fox jumps over the lazy dog."))."\n";
?> 
<?php
$x =  20;            // $x is an integer
$str1 = (string)$x; // $str1 is a string now
// Check whether $x and $str1 are equal or not
if ($x === $str1) 
{
  echo "They are the same"."\n";
}
else
{
echo "They are not same"."\n";
}
?> 
<?php
function my_sqrt($n)
{
  $x = $n;
  $y = 1;
  while($x > $y)
  {
    $x = ($x + $y)/2;
    $y = $n/$x;
  }
  return $x;
}
print_r(my_sqrt(16)."\n");
print_r(my_sqrt(14)."\n");
?>

End function can set the pointer of an array to the last element of array.

<?php
$arr               =  array('name'=>'angel' ,'city'=>'delhi' ,'profession'=>'web developer');                                
$lastValue     = end($arr);
?>

$this is called pseudo variable and this is availabel when a method is called from within an Object context. $this is refrence to the calling object of the current class. When we need to call a method of a class within the same class instead of creating object of that class we can use $this to call the method of the existing class.

<?php
 
Class A
{
  public function getName()
  {
    $name = '';
    return $name;
  }

  public function getUserDetails()
  {
    $this->getName();              // to call the other method of the class we can use this operator.
   
  }

}

  $obj = new A();
  echo $obj->getUserDetails();
 
?>
 <?php
function quick_sort($my_array)
 {
	$loe = $gt = array();
	if(count($my_array) < 2)
	{
		return $my_array;
	}
	$pivot_key = key($my_array);
	$pivot = array_shift($my_array);
	foreach($my_array as $val)
	{
		if($val <= $pivot)
		{
			$loe[] = $val;
		}elseif ($val > $pivot)
		{
			$gt[] = $val;
		}
	}
	return array_merge(quick_sort($loe),array($pivot_key=>$pivot),quick_sort($gt));
}
 
$my_array = array(3, 0, 2, 5, -1, 4, 1);
echo 'Original Array : '.implode(',',$my_array). PHP_EOL;
$my_array = quick_sort($my_array);
echo 'Sorted Array : '.implode(',',$my_array). PHP_EOL;
?>
<?php
$original = array( '1','2','3','4','5' );
echo 'Original array : '."\n";
foreach ($original as $x) 
{echo "$x ";}
$inserted = '$';
array_splice( $original, 3, 0, $inserted ); 
echo "\n After inserting '$' the array is : "."\n";
foreach ($original as $x) 
{echo "$x ";}
echo "\n"
?>
<?php
$month_temp = "78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73";
$temp_array = explode(',', $month_temp);
$tot_temp = 0;
$temp_array_length = count($temp_array);
foreach($temp_array as $temp)
{
 $tot_temp += $temp;
}
 $avg_high_temp = $tot_temp/$temp_array_length;
 echo "Average Temperature is : ".$avg_high_temp."
"; 
sort($temp_array);
echo " List of seven lowest temperatures : ";
for ($i=0; $i< 5; $i++)
{ 
echo $temp_array[$i].", ";
}
echo "List of seven highest temperatures : ";
for ($i=($temp_array_length-5); $i< ($temp_array_length); $i++)
{
echo $temp_array[$i].", ";
}
?>
<?php
$n=range(11,20);
shuffle($n);
for ($x=0; $x< 10; $x++)
{
echo $n[$x].' ';
}
echo "\n"
?>
<?php
function min_values_not_zero(Array $values) 
{
return min(array_diff(array_map('intval', $values), array(0)));
}
print_r(min_values_not_zero(array(-1,0,1,12,-100,1))."\n");
?>
<?php
$colors = array("Red", "Orange", "Black", "White");
rsort($colors);
print_r($colors);
?> 
<?php
$my_text = 'The quick brown [fox].';
preg_match('#\[(.*?)\]#', $my_text, $match);
print $match[1]."\n";
?>
<?php
$string = 'abcde$ddfd @abcd )der]';
echo 'Old string : '.$string."\n";
$newstr = preg_replace("/[^A-Za-z0-9 ]/", '', $string);
echo 'New string : '.$newstr."\n";
?>
<?php
$json = '{"number": 123456789012345678901234567890}';
var_dump(json_decode($json));
?>