PHP Cheatsheet

Common PHP Functions and Statements
Code Usage Description
include <?php include 'footer.php';?> The include statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.
empty() if (empty($var1)) {
echo '$var1'." is empty. <br>";
}
Check whether a variable is empty
echo() echo "Hello world!" The echo() function outputs one or more strings.
printf() $str="rachel"
printf("Hi %s", $str);
The printf() function outputs a formatted string.
isset() if (isset($gender)
  ...
The isset () function is used to check whether a variable is set or not.
sort()
rsort()
asort()
ksort()
arsort()
krsort()
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age)
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key
array_search() $a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
Search an array for the value and return its key

PHP Arrays
Array Type Usage Description
Indexed Arrays $cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
echo count($cars)

Or assign like:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
These are our typical arrays that store multiple values in a single variable.
Associative Arrays $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

echo "Peter is " . $age['Peter'] . " years old.";

foreach($age as $x => $x_value) {
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "<br>";
}

OR assign like:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Associative arrays are arrays that use named keys that you assign to them.

PHP Superglobals
Superglobal Usage Description
$_GET echo "Study " . $_GET['subject'] . " at " . $_GET['web']; PHP $_GET can be used to collect form data after submitting an HTML form with method="get".
$_POST $name = $_POST['fname']; PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.
$_SERVER Examples:
if($_SERVER["REQUEST_METHOD"]=="POST"){
  if(isset($_POST["uname"])&& isset($_POST["pass"])){
    ...
  }
}
$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

For more on PHP Go to: http://www.w3schools.com/jsref/default.asp where many of the above examples and descriptions come from.