Close

PHP language Quick Reference Guide

[Last Updated: Oct 29, 2018]

PHP (Hypertext Preprocessor) is interpreted language. It's famous of being server side scripting language but can be used as general purpose, stand-alone or command line programs as well.

Following a quick walk through of PHP language basic features.


Steps/Features/Syntax Description/examples
Typically php file extension has to be .php Php interpreter is invoked on finding .php files.
.php file can contain just PHP or mixed PHP and HTML code It can also contain JavaScript, CSS, XML or just plain text etc
<?php
      //php code here
 ?>
PHP interpreter executes php code written within these tags to generate dynamic web pages or other contents. Also
  • If the file just have PHP code, closing ?> can be skipped (recommended)
  • // or # or /* ... */ are used for comments
  • Each statement must be terminated with ;
  • Short form of tags <?= ... ?> (returns and print the value) or <? ... ?> executes the PHP code;
Downloading and running
  1. Download php here.
  2. Set the path of main installed folder (where there's 'php' executable e.g. php.exe on windows).
  3. Run built-in server from cmd, from root of your code project:
    php -S localhost:8080
  4. Accessing from browser, e.g: localhost:8080/Test.php
  5. Use Notepad++ for editing php files or IDE like 'Eclipse for PHP Developers' which is free and has advance features like formatting, ref suggestions, PHP-CLI integration etc.
Text output
echo 'hello';
echo can take multiple comma separated strings.
Alternatives:
  1. print: takes single string argument
  2. printf: outputs the C style formatted string.
  3. sprintf() function returns a formatted string instead of outputting.
Declaring variables
<?php
$i = 3;
$j = 1.45;
$str = "Hi there!";
?>
A variable always starts with the $, it can be alpha-numeric but cannot start with a number. PHP is not typed language so no type declaration.
Implicit data types:
  • boolean
  • integer
  • float (double)
  • string
  • array e.g: $users = array("Steve", "Jenny");
  • object e.g. $role = new Role('admin')
  • null e.g. $a = null;
  • resource e.g: $myDir = opendir('d:\test');
Note that type of a variable is decided based on what value is assigned to it. For example, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.
PHP is not case sensitive We can use ECHO or Echo etc. Only Variable names are case sensitive.
Strings' single quotes vs double quotes Unlike single quotes, double quotes evaluate variables.
 $s = "Hey";
 echo '$s there.'; // $s there.
 echo "$s there."; // Hey there.
 echo "{$s}y there."; // Heyy there.
In above example we used curly brackets {$...} which allows for variable separation from literals and complex expressions e.g. "{$myObject-> myProp} ...", "item: {$arr[4][3]}" etc. .

Quotes used within quotes must be escaped :
 echo "{$s} \"you\" there"//hey! "you" there
Heredoc: <<<A_LABLE ..
It's like double quotes but supports multi-lines and no need to escape
$s = "Hey";
echo <<<myLabel
$s,
How are "you" doing?
myLabel;
Output:
Hey, How are "you" doing?
NowDoc <<<'A_LABLE' ..
Similar to Heredoc but no variable parsing. Good for embedding php or other code.
$s = "Hey";
echo <<<'myLabel'
$s,
How are "you" doing?
myLabel;
$s, How are "you" doing?
String concatenation
The dot (.) operator.
echo 'name = '.$name. ', email = '.$email;
Variable assignment by value
By default variables are assign to each other by value. That means value of the original variable is copied into the destination variable.
<?php
$a = 'value a';
$b = 'value b';

//variable assignment by value
$b = $a;
$b = "new value of b";

echo "$a <br/>";
echo "$b <br/>";
?>
Output:
value a
new value of b
Variable assignment by Reference
This means that the new variable simply references the original variable. Technically speaking they point to the content of the variable after the assignment. Changes to the new variable affect the original, and vice versa.
We use & operator for reference assignment as shown in the example.
<?php
$a = 'value a';
$b = 'value b';

//variable assignment reference
$b = &$a; //prepend  &, this is the only change
$b = "new value of b";

echo "$a <br/>";
echo "$b <br/>";
?>
Output:
new value of b
new value of b
Functions: A function can have any number of arguments. An argument can have a C++ style default value and can optionally return a value.

Ideally defaults arguments should be at the end of non-default arguments otherwise there won't be any use of having them because we always have to pass their values in function call.

Built-in functions
PHP provides various built-in functions. Those functions include string manipulation, math, array functions. var_dump($someVar) is very useful to display structure information of a variable.
Defining a function
<?php
//defining function
function myFunctionName($myArg1, $myArg2,
                          $myArgWithDefault = true) {
     // apply some code logic
    return "$myArg1, $myArg2 , $myArgWithDefault";
}

//calling function
echo myFunctionName('some value', 5);
?>
Output: some value, 5 , 1
Functions:
Passing arguments by reference.

Prepend & to the argument.
A function can have mixed 'by values' and 'by reference' args.
<?php
function someFunction(&$someArg) {
   $someArg = 10;
}

$aNumber = 4;
someFunction($aNumber);
echo $aNumber;
?>
Output: 10

A function can return value by reference as well. Use the reference operator & in both the function declaration and when assigning the returned value to a variable:
<?php
function &someFunction() {
  static $val = 5;
  echo "value of val = $val <br>";
  return $val;
}

$var = &someFunction();
$var = $var + 4;
$var = someFunction();
?>
Output:
value of val = 5
value of val = 9 
Functions:
Type declarations.

Function arguments can now have types so that caller cannot pass wrong values:
Since PHP 7.0.0 :
bool , float, int, string
Since PHP 5.x:
array, callable, self, a Class/interface name.
Types are added before an arg name e.g.
  function myFunc(bool $myBool, int $myInt) {...}

Above types are loosely typed, that means an arg of string type can accept an int because an int is still convertible to string. But by declaring the script as strict_types=1 that cannot happen, i.e. it achieves strong typing:

<?php
  declare(strict_types=1);

  function myFunc(bool $myBool, int $myInt) {...}

  ...
?>

Starting PHP 7, functions return values can also be typed. For example:
 function myFunc() : int {...}
We can also achieve strict typing for return type by using declare(strict_types=1); just like arguments.
Variable-length argument
Since PHP 5.6 variable-length argument lists can be defined by using ... with method arguments.

It's just like C++ variadic functions and Java varargs.

Also a similar syntax e.g ...[1,2] can be use when calling a function.

For Older versions of PHP, no ... required; however to access function's multiple arguments, the function must use func_num_args(), func_get_arg() and func_get_args().
For 5.6+
<?php
function aFunction(... $vars){
    //better use foreach loop here
    echo "$vars[0], $vars[1], $vars[2]<br>";
}

aFunction("one", "two", "three");
?>
one, two, three
For older versions (it will give same output)
<?php
function aFunction(){
   $vars = func_get_args();
   echo "$vars[0], $vars[1], $vars[2]<br>";
}

aFunction("one", "two", "three");
?>
Using variable-arg assignment on function call (works for 5.6+)
<?php
function aFunction($a, $b){
   echo "$a, $b<br>";
}

aFunction(...["one", "two"]);
?>
one, two

In above example we could have used variable arg syntax at both places, at function definition and at function call.

Function inside another function

A function can have any valid code including other functions and class definitions.

A function can also be defined conditionally (e.g. in if block).

 <?php
function aFunction(){
  echo "From a function<br/>";

  function aLocalFunction(){
    echo "From a local function</br>";
  }
}

aFunction();
aLocalFunction();
?>
From a function
From a local function
Note that calling 'aLocalFunction' before 'aFunction' will give undefined function error because aLocalFunction haven't defined (or doesn't exist) before we call the outer function 'aFunction'.
Scope of variables:
  • Variables defined outside a function are 'global variables', a function cannot access them.

  • Variable defined inside a function are 'local variables' and not accessible outside.

  • Local variables defined with global keywords can use variables defined outside. Alternatively PHP special array $GLOBALS can be used to achieve the same. $GLOBALS is an associative array containing references to all variables which are defined in global scope of the script. This array also contain other super-global variables. $GLOBALS itself is super-global
Note: Even though a function cannot access variables defined outside, but it can call other functions defined outside.
Also all scopes are limited to the current files, we cannot access other .php file variables/function until we include them in the current file.
<?php
$firstName = 'Steve';
$location = 'Alaska';
$zip = '11111';

function modifyUser() {
   echo "--- inside the function --- <br/>";
   $lastName = 'Willams';
   echo "firstName locally = $firstName <br/>";
   //using global keyword
   global $location;
   $location = 'Hawi';
   //alternative way to use global
   $GLOBALS['zip'] = '22222';
}

modifyUser();
echo "--- outside the function --- <br/>";
echo "firstName = $firstName <br/>";
echo "lastName = $lastName <br/>";
echo "location = $location <br/>";
echo "zip = $zip <br/>";
?>
--- inside the function ---
firstName locally =
--- outside the function ---
firstName = Steve
lastName =
location = Hawi
zip = 22222
Local static variables:
A static variable declared locally does not lose it's value when method exits. That means subsequent executions will use the previous values.

This feature is useful for recursive logic.

Note that static variables can be initialized by expressions, but not by a function call. (see the commented line in example: static $result = getInitialValue();)
<?php
function aFunction() {
  //static $result = getInitialValue(); this will cause syntax error
  static $result = 4;// initializes only once
  $result = $result +1;
  return $result;
}

function getInitialValue(){
  echo 'getInitialValue called';
  return 4;
}

echo aFunction().'<br/>';
echo aFunction().'<br/>';
echo aFunction().'<br/>';
?>
Output:
5
6
7
Anonymous functions
These are functions without names. They can be assigned to a variable, which can be passed as other function parameter, hence allowing functional programming in PHP.
They are also called closures.

Note, closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. This is shown in the last example.

Inheriting variables from the parent scope is not the same as using global variables. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).
<?php
function aFunction($var){
   echo $var();
}

aFunction(function(){
 return "from a closure";
});
?>
Output: from a closure Assigning to a variable which gives the same output:
<?php
function aFunction($var){
  echo $var();
}

$myFunc = function(){
  return "from a closure";
};

aFunction($myFunc);
?>
Closures can also inherit variables from parent scope by using 'use' keyword:
<?php
$myVar = 10;

function aFunction($var){
  echo $var();
}

$myFunc = function() use ($myVar){
  return "from a closure with global var = $myVar";
};

aFunction($myFunc);
?>
from a closure with global var = 10
Callback functions:
A function can be called by it's name as a string. It's like function pointer which can be used for dynamic method invocation.

PHP built-in function call_user_func is used to invoke a callable function. This function takes the name of function as first parameter and remaining parameters are used to pass function parameters.
<?php
function aFunction($var){
  echo "in the function var = $var <br>";
  return "theReturnedValue";
}

echo call_user_func('aFunction', 'somePassedVariable');
?>
 

Variable variables

It is variable nesting. The variable name is dynamically evaluated from one or more nested variables using syntax:
$$someVariableNameReference
<?php
$name = 'Mike';
$var = 'name';
echo $$var;
?> 
Output:
 Mike
Note we can use ${$var} instead of $$var for clarity.

Variable function

If a variable has parentheses appended to it, PHP will look for a function with the same name the variable name, and will attempt to execute it. Useful for dynamic function execution.

The built-in function is_callable() can be used to verify that a variable can be called as a function

<?php
function myFunction() {
   echo 'inside myFunction';
}

$var = "myFunction";
if (is_callable($var)) {
   $var();
}
?>
Output:
inside myFunction

Constants

The variables which cannot be changed after declaration.
Syntax:
define(name, value, case-insensitive[true/false])
default case-insensitive value is false.
Constants are implicitly global.
Magic Constants: These are predefined constants: __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS_, __TRAIT__, __METHOD__, __NAMESPACE__

constant ( string $var ) returns the value of constant by a variable or a function return value. Useful when we don't know the constant name.

bool defined (nam ) checks if a variable exists.

Keyword const

Starting 5.3 we can also use the keyword const to define constants (it was only allowed within a class definition only before):
const XYZ = 'A constant value';
As opposed to 'define' they are compile time constants (just like static final variables in Java) that's why they cannot be inside a function but can be defined inside a class. The value assign must be a scalar value or scalar expression.

<?php
define ( "MAX_COUNT", 10 );

function myFunction() {
	if (defined("MAX_COUNT")) {
		echo MAX_COUNT;//same as echo constant("MAX_COUNT")
	}
}

myFunction ();
?>
Output:
10

Using const:
<?php
const X = 2 * 3;
const Y = 'constant y value';
$var = 5;
//cont Z = $var does not work
echo X . '<br>';
echo Y;
6 constant y value

Operators

Arithmetic Operators:

+ addition
- subtraction
* multiplication
/ division
% modulus
** exponent

Assignment Operators:

= right side to left side value assignment,
$var = $other
+= add and assign $var+= $other ($var=$var+$other)
-= subtract and assign $var-= $other ($var=$var-$other)
*= multiply and assign $var*= $other ($var=$var*$other)
/= divided and assign $var/= $other ($var=$var-$other)
%= modulus and assign $var%= $other ($var=$var%$other)

Comparison Operators:

== equal
=== equal and same type
!= or <> not equal
!== not equal or not same type
> greater than
< less than
>= greater than and equal
<= less than and equal

Increment/decrement Operators:

++$anInt pre-increment
$anInt++ post-increment
--$anInt pre-decrement
$anInt-- post-decrement

String Operators:

. dot, concatenation
($str1 . $str2)
.= concatenate and assign
($str1 .= $str2)

Logical Operators:

$a and $b
$a && $b
TRUE if both $a and $b are true
$a or $b
$a || $b
TRUE if either $a or $b is true

Array Operators:

+ union ($array1 + $array2)
Array also supports all
comparison operators
except for less than
and greater than ones.

Conditional statements

PHP's 'if' structure is similar to C++
if (boolean-expression){
 //some code
}
<?php
if ($x > 5){
 echo 'x is greater than 5';
}
?>

if the expression inside 'if' is not boolean but evaluates to 0 then it's treated as false otherwise true.

<?php
$i = 0; //or even $i="0";

if ($i) {
  echo 'i is not zero';
} else {
  echo 'i is zero';
}
?>

Output: i is zero

if/else combination:
if(boolean-expression){
 //some code
} else {
 //alternative code
}
<?php
if ($x > 5){
 echo 'x is greater than 5';
} else {
 echo 'x is less than 5';
}
?>
if/elseif/else or
if/else if/else:
if(boolean-expression){
 //some code
} else if (boolean-expression2){
 //some other code
} else {
 /*this must get executed if all are false*/
 }
<?php
if ($x > 5){
 echo 'x is greater than 5';
} else if ($x < 0) {
 echo 'x is less than 5 and negative';
} else {
 echo 'x is between 0 and 5 inclusively';
}
 ?>

Other if/else syntax:

<?php if ($x > 5): ?>
 A is greater than 5
<?php endif; ?>
<?php
if ($a == 5):
echo "a equals 5";
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
else:
echo "a is neither 5 nor 6";
endif;
?>

Ternary Operator

It is another conditional operator and is combination of ?and :

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, otherwise it evaluates to expr3. It can be nested as well:

<?php
$a = 9;
echo "The number $a is ".($a<6? 'less than': ($a==6? 'equal to': 'more than')).' 6';
Output: The number 9 is more than 6

switch Statement

switch is alternative way to write if/elseif/else blocks but it only works on discrete values specified with case keyword:

<?php
$x = 0;
switch ($x) {
case 5 :
echo "x equals 5";
break;
case 0 :
echo "x equals 10";
break;
default :
echo "value of x is $x";
}
?>
   

Loops

while loop

The while loop executes a block of code as long as the specified condition is true.

while (boolean expr){
statement
}
<?php
$a = 1;

while($a <= 5) {
 echo "value of a= $a <br>";
 $a++;
}
?>

do/while loop

This loop runs the code block first then checks the condition.

do {
} while(boolean expr);


<?php
$a = 1;

do {
  echo "value of a = $a <br>";
  $a++;
} while ($a <=5);
?>

for loop

C like for loops where expressions are evaluated before and after a middle boolean condition.

for (expr1; boolean expr2; expr3){
    statement
}
<?php
   for ($a = 1; $a <= 10; $a++) {
   echo "value of a = $a <br>";
}
?>

foreach loop

This loop works only on arrays and objects.

foreach (array_expression as $value){
    statement
}
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
  echo "array element: $value <br>";
}
?>

foreach index/value associativity

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => $value) {
  echo "array element: $key = $value <br>";
}
?>
Output:
 array element: 0 = 1
 array element: 1 = 2
 .....

foreach key/value associativity

<?php
$arr = array("Feb" => 28, "April" => 30);
foreach ( $arr as $key => $value ) {
   echo "array element: $key = $value <br>";
}
?>

Output:

array element: Feb = 28
array element: April = 30

Controlling loop

Using 'break' inside loops

The keyword 'break' ends execution of the current loop structure (that includes switch statement). An optional numeric argument e.g. 'break 2' specifies how many levels to be broken out (used inside nested loops), default is 1.

Using 'continue' inside loops

The keyword 'continue' is used to skip the rest of the current loop execution and continue with the next iteration. Just like 'break', 'continue' can also be used with an optional numeric value specifying how many level to be continues in case of various nested loops.

Arrays:

Arrays in php are ordered map.

They can be used as an array, collection, map etc.

An array can be multidimensional i.e. an array element can be other array.

Arrays are created by using array(..) construct or starting PHP 5.4 we can use [...].

Array functions:

count($anArray) to get array length.
is_array($aVar) finds whether a variables is an array.
array_key_exists('aKey', $anArray) Checks if the given key or index exists in the array.
Here's the complete list of array functions.

Indexed array

$x = ["Feb", "April"];
echo "$x[0] <br>";
echo "$x[1] <br>";
Output:
Feb
April

A map also known as associative array

$arr = ["name" => "Steve", "age" => 30];
foreach ( $arr as $key => $value ) {
	echo "array element: $key = $value <br>";
}

Multidimensional

$arr = ["name" => "Steve", "orders"=> [1,2,3]];

String functions and conversions:

PHP provides many built-in string function which includes trimming, accessing chars, splitting, joining, formatting, conversion to/from html entities, searching index, lower/upper case, sub-strings etc. A complete list of string functions is here.

Additionally, we can access string characters like an array e.g. $aString[1].

Other types can be converted to string by explicit casting or using strval() function. An integer or float can be converted to string and vice versa. The string conversion can be implicit depending on the context e.g. echo "a boolean $boolVar", if boolVar is true it will be converted to 1 otherwise to "" empty string.

A negative index to substr will get a sub-string from the end.
$str = "Learning php";
echo substr($str, -3);

Output php

$arr = [1,3,5];
echo "$arr[2]";
Output: 5

5+ "2" will be 7 of type integer. Also this kind of conversion is allowed:

echo 5 + "6 apples";

Output: 11

Splitting and iterating:
$str = "this is one string";
foreach (str_split($str) as $v){
  echo $v. "<br>";
}

include/require statements

These functions allow to include other php, html or txt file within the current php file.

Difference between the two function is: require() produces fatal error, whereas, include produces warning.

The path specified can be relative or absolute. We can also use direname(__DIR__) which gives the absolute path of current dir to prepare the target file path.

If complete path is not specified but just file name e.g. include('fileName.php'), and php.ini (the main php configuration file) has 'include_path' specified then it's used to search the target file.

If a file contains a function, including it multiple time will cause error. Use include_once or require_once in that case.

includeTest.php file:
<?php
function myFunction($var){
 echo "from myFunction $var";
}
?>
includeTest2.php
<?php
include 'includeTest.php';
myFunction("hi there!");
?>
includeTest2.php gives this output:
from myFunction hi there!

Null checking

<?php
$var;
echo isset($var) ? 'value='.$var : 'not set';//not set
echo is_null($var) ? 'null' : 'not null';//null
echo $var == NULL? 'null': 'not null';//null
echo $var === NULL? 'null': 'not null';//null
echo $var?  'value='.$var : 'not a valid value';//not a valid value;

$var = null;
echo isset($var) ? 'value='.$var : 'not set';//not set
echo is_null($var) ? 'null' : 'not null';//null
echo $var == NULL? 'null': 'not null';//null
echo $var === NULL? 'null': 'not null';//null
echo $var?  'value='.$var : 'not a valid value';//not a valid value;

$var = '';
echo isset($var) ? 'value='.$var : 'not set';//value=
echo is_null($var) ? 'null' : 'not null';//not null
echo $var == NULL? 'null': 'not null';//null
echo $var === NULL? 'null': 'not null';//not null
echo $var?  'value='.$var : 'not a valid value';//not a valid value;

$var = 5;
echo isset($var) ? 'value='.$var : 'not set';//value=5
echo is_null($var) ? 'null' : 'not null';//not null
echo $var == NULL? 'null': 'not null';//not null
echo $var === NULL? 'null': 'not null';//not null
echo $var?  'value='.$var : 'not a valid value';//value=5;


See Also