All keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive, but all variable names are case-sensitive.
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
PHP has three different variable scopes:
local
global
static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
To access a global variable from within a function, use the global before the variables:
$x = 5; $y = 10; function myTest() { global $x, $y; $y = $x + $y; } myTest(); echo $y; // 15
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:
$x = 5; $y = 10; function myTest() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } myTest(); echo $y; // 15
The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. If you want the variable to persist, however, you can use the static keyword when you first declare the variable:
function myTest() { static $x = 0; echo $x; $x++; } myTest(); myTest(); myTest();
Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.
Note: The variable is still local to the function.
echo and print Statements
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
The echo statement can be used with or without parentheses: echo or echo().
The print statement can be used with or without parentheses: print or print().
Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
String
Integer
Float (floating point numbers – also called double)
Boolean
Array
Object
NULL
Resource
String
A string is a sequence of characters, like “Hello world!”. A string can be any text inside quotes, either double or single.
Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based – prefixed with 0x) or octal (8-based – prefixed with 0)
In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
$x = 5985;
Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The var_dump() function returns the data type and value:
$x = 10.365;
var_dump($x);
Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Array
An array stores multiple values in one single variable.
Object
An object is a data type which stores data and information on how to process that data.
Objects must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties and methods:
class Car { function Car() { $this->model = "VW"; } } // create an object $herbie = new Car(); // show object properties echo $herbie->model;
NULL
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
$x = "Hello world!"; $x = null; var_dump($x);
Resource
The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.
Constants
Constants are like variables except that once they are defined they cannot be changed or undefined.
A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Note: Unlike variables, constants are automatically global across the entire script.
Default for case-insensitive is false.
define("GREETING", "Hello!", true); echo greeting; function myTest() { echo GREETING; } myTest();
Sort Functions For Arrays
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
Superglobals
Several predefined variables in PHP are “superglobals”, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file.
The PHP superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
GET vs. POST
Both create an associative array holding key/value pairs, where keys are the names of the form controls and values are the input data from the user.
$_GET and $_POST are both superglobals, which means that they are always accessible, regardless of scope.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET should only be used for sending non-sensitive data, definitely not passwords etc.
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
SALT
Password salting is a technique which is widely used to secure passwords by randomizing password hashes, so that if two users have the same password, they will not have the same password hashes. This is done by appending or prepending a random string, called a salt, to the password before hashing.
<?php date_default_timezone_set( "Australia/Sydney" ); //if...else...elseif $time = date("H"); if ($time < "10") { echo "Have a good morning!"; } elseif ($time < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } //Use the switch statement to select one of many blocks of code to be executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found. $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } //while loop $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } //do...while loop //The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. $x = 1; do { echo "The number is: $x <br>"; $x++; } while ($x <= 5); //for loop //The for loop is used when you know in advance how many times the script should run. for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } //foreach loop //The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } //Default arguments in functions function setHeight($minheight = 50) { echo "The height is : $minheight <br>"; } setHeight(350); // 350 setHeight(); // will use the default value of 50 /* Superglobal variables: $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION */ /* Three types of arrays: Indexed arrays - Arrays with a numeric index Associative arrays - Arrays with named keys Multidimensional arrays - Arrays containing one or more arrays */ //array() function creates an array $arr = array(); $myarray = array(); //this line necessary? $myarray[0] = "Vanessa"; $myarray[1] = "Alice"; $myarray[2] = "Rebecca"; //Or #$myarray = ("Vanessa", "Alice", "Rebecca"); print_r($myarray); var_dump($myarray); //get the length of an array echo count($myarray) . "<br>"; //add item $myarray[] = "Kelly"; array_push($myarray, "Chloe"); var_dump($myarray); //implode() echo implode(" - ", $myarray) . "<br>"; //loop indexed array $arrlength = count($myarray); for($i = 0; $i < $arrlength; $i++) { echo $myarray[$i] . "<br>"; } //foreach foreach($myarray as $name) { echo $name . "<br>"; echo "Name is: $name <br>"; echo "NAME is {$name} <br>"; } //while loop $num = 3; $i = 0; while ($i < $num) { $namenum = $i + 1; echo "Name $namenum is: $myarray[$i]<br>"; ++$i; } echo "<h3>Associative</h3>"; //create an associate array $age = array( "Vanessa" => 35, "Alice" => 25, "Rebecca" => "twenty eight" ); //Or $age = array(); $age['Vanessa'] = 35; $age['Alice'] = 25; $age['Rebecca'] = "twenty eight"; //loop associative array foreach($age as $key => $value) { echo $key . " : " . $value . "<br>"; } echo "<h3>Multi-dimensional</h3>"; $flower_shop = array( "rose" => array( "5.00", "7 items", "red" ), "daisy" => array( "4.00", "3 items", "blue" ), "orchid" => array( "2.00", "1 item", "white" ), ); ?>