Logo  

CS479/579 - Web Programming II

PHP

The PHP engine only interprets PHP code that is found within <?php ... ?> sections. Everything else is just "printed/transmitted" as normal text (called "output".)

"Hello, world!" Example:

<?php
  echo "Hello, again!";
?>

Variables:

  • May contain any type (loosely typed)
  • prefixed by a dollar sign ($)
  • May start with a letter or underscore, then may be followed by any alpha- numeric character (a-zA-Z0-9) and underscores.
  • Have three different scopes:
    • local - Variable is only visible to the function it is defined in.
    • global - Variable is visible to all functions. Global variables must be declared as global in a function in order to use it in the function.
    • static - Variable only exists in a function, but does not lose its value between function calls (i.e. it's allocated on the heap, not the stack)

Example:

<?php
  $g = 5; // global scope

  function foo() {
    // global $g;
    // using g inside this function will generate an error unless the above is un-commented
    echo "Variable g is: $g\n";
  }
  foo();
  echo "Variable g outside function is: $g\n";
?> 

Data types:

Boolean:

$x = true;
$x = false;

Integers:

$x = 123;   // Decimal
$x = 0xff;  // Hexadecimal
$x = 0777;  // Octal
  • Convert to an integer using a cast (int), like in C:
    $x = (int)"123";

Float (doubles):

$x = 1.25;
$x = 10E+5; // Exponential form
  • cast (float) to convert to floating-point.

  • is_nan($x) to test if a number or not.

Strings (single or double quoted):

Single quoted strings do not interpret variables or back-slashed escapes for special chars:

$x = 'abc';

Double quoted strings expands variables and escapes for special chars:

$x = "abc";

Executes the unix command placing it's output where the ``'s are:

$x = ` command ` ;

(Bash) Heredoc syntax for multi-line strings, text between a <<<label and ending with the same label are the string. Otherwise work like double-quoted strings:

$x = <<<EOM
    text...
EOM


Nowdoc: Like heredoc above, but the initial label is single quoted. There will be no parsing, just like inside a single quoted string:

$x = <<<'EOM'
  text...
EOM

Embedding variables in strings:

Simple syntax:

".. $name ..", "...${name}abc"
".. $name[0] ..", ".. $name[key] .."

Complex syntax:

"..{$vardesc}..": "..{$name[0][1]}.."
"..{$name['key']}.." "..{$class->method()}.."

It is recommended to always use complex syntax, since it will avoid any issues with the surrounding text, and is more flexible.

Misc string functions:

strlen($str) Length of a string
explode($sep, $str [,$limit]) Splits the string $str into an array of strings separated by $sep
ltrim($str [,$chars]) Removes white-space or characters from $chars from the left side of the string
rtrim($str [,$chars]) Removes white-space or characters from $chars from the right side of the string
trim($str [,$chars]) Removes white-space or characters from $chars from the both sides of the string
C string functions PHP also has most C style string functions


To convert a different type to a string, use a (string) cast or the strval() function.

$x = 10;
$s = (string)$n;

Arrays:

PHP arrays are really maps/dictionaries (in the form of key => value). Simple arrays are just the numeric keys starting at 0. When using a string constant as a key, it should be single or double quoted, i.e.: $var['foo']

PHP arrays are defined using the array() function. Each element of an array may have its own data-type.

<?php
  $x = array("a", "b", "c");
  $x = array(1, "b", true);
  var_dump($x);
?>


To make sparse arrays or dictionaries, use the 'key => value' syntax:

$x = array("name" => "Steve", "age" => 46);

To get the number of elements in an array use the count function:

count(array $value);

Though sizeof can be used to get the size of of an array, it is just an alias for count, so use count instead. Aliases tend to get deprecated, also sizeof introduces confusion among C programmers.

list() assignment from arrays:

The list() operator allows one to assign the values of an array to individual variables in one assignment:

list($var1, $var2, ... $varN) = array $value;

<?php
  $foo = array("Bob", "Smith", 45);
  list($fname, $lname, $age) = $foo;
?>

Objects:

An object must be declared, then a variable can be assigned an instance of an object via "new".

<?php
class Dog {
  // __construct is the object constructor function:
  function __construct($name) {
    $this->name = $name;
  }
}
$dog = new Dog("Spot");
echo $dog->name . "\n";
?>

null:

The default value for a variable that hasn't been given one.

Setting a variable to null will empty it and release its contents.

$x = null;

Resources:

Used for things like file descriptors, or network handles or pointers to functions.

Constants:

Defined with:

define(string $name, mixed $value [,bool $case_insensitive=false])

mixed = (boolean, integer, float and string), array added in PHP7.

Constants have super global scope.

Inside classes, to declare a constant, use:

const name = value;

define() does not work inside of classes.

Super-Globals:

Super-globals are special PHP variables that are available at all scopes and do not need to be declared global within a function.

Variable Maps:
$GLOBALS All variables available in global scope.
$_SERVER Server and execution environment information
$_GET HTTP GET variables
$_POST HTTP POST variables
$_FILES HTTP File Upload variables
$_COOKIE HTTP cookies
$_SESSION Session variables
$_REQUEST HTTP Request variables (contains the contents of $_GET, $_POST and $_COOKIE)
$_ENV Environment variables

Expressions:

Everything C has plus:

$a ** $b Exponentiation ($a to the $b-th power)
$a == $b Equality after type-juggling
$a === $b Strict equality (types must match)
$a <> $b Same as $a != $b
$a !== $b Strict inequality
$a <=> $b Gives an int <, > or == to 0, when $a is <, > or == to $b (like C's strcmp function)

Error control operator: @

Prepend @ to almost anything that can give a value and PHP will ignore any errors that it might produce. (sets logging level to 0?)

Example:

<?php
/* Intentional file error */
$my_file = @file ('non-existent-file') or
   die("Failed opening file: error was:". error_get_last()['message'] . "\n");
// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
echo $value;
?>

Execution operator:

Back-ticks `...`, like a unix shell, the Unix command within the backticks is executed and the output of the command becomes the string value, example:

<?php
  // Executes 'ls -la' and assigns the output of it to $output:
  $output = `ls -la`;
  echo "<pre>$output</pre>";
?>
  • Note: this is dangerous when using any non-validated inputs in the string. Use with caution.

Logical operators:

and, or and xor in addition to &&, || and !

examples:

$foo = $a and $b; $bar = $a xor $b;

String concatenation operator: (.)

The period is the string concatenation operator in PHP, do not use + for string concatenation (PHP is not ECMAScript).

"abc" . "def" == "abcdef"
$x .= "abc"; ──► $x = $x . "abc";

Array operations:

$a + $b Union of $a and $b
$a == $b TRUE if $a and $b have the same key/value pairs.
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types. (strict equality)
$a != $b Inverse of above, also $a <> $b
$a !== $b Strict inequality

Control structures:

There is an alternative syntax for control structures. Replace the opening { with a : (colon) and ending } with a end*; for the control structure, i.e.:

while (expr):
  ...
endwhile;

This alternative syntax is to make control structures mixed with embedded output clearer. i.e. instead of:

<?php if (expr) { ?>
  HTML output
<?php } ?>

you can use:

<?php if (expr): ?>
  HTML output
<?php endif; ?>

The endif; part helps to disambiguate what control structure it belongs to above, particularly if you are using multiple control structures.

  • Don't try to mix standard and alt syntax, example:
<?php
if (expr):
  echo "...";
else {
  echo "...";
}
?>

Conditionals:

If:

if ( expr ) statement
[else if ( expr ) statement]
[elseif ( expr ) statement]
[else statement]

or alt syntax (note: no 'else if:')

if ( expr ):
[elseif ( expr ):]
[else:]
endif;

Switch:

switch( expr ) {
[case constant:]
[default:]
}

Note that continue inside a switch works just like break, so if you want to continue a loop from within a switch, you will need to use "continue 2;"

Alternate syntax:

switch( expr ):
[case const:]
[default:]
endswitch;

There can be no output between the switch(expr): line and first case.

Loops:

While:

while ( expr ) statement

or:

while ( expr ):
...statements
endwhile;

Do-while:

do statement while( expr );

  • There is no alt syntax for a do-while.

For:

for(init-expr; test-expr; inc-expr ) statement

or:

for(init-expr; test-expr; inc-expr ):
...statements
endfor;

Foreach:

foreach(array_expr as $value ) statement

or

foreach(array_expr as $key => $value ) statement

A foreach loop iterates over array_expr, placing the values into $value (and key into $key if using the second form) each at a time.

If you want to change the value using $value, you must make it a reference by prefixing a ampersand (&). i.e.:

foreach($array as &$value) $value *= 2;

NOTE: unset($value); afterward as $value will remain as a reference to the last element in the array, so if you use $value again, it will overwrite it.

Functionally equivalent to:

reset($array);
while(list(,$value) = each($array)) statement;

or

while(list($key, $value) = each($array)) statement;

Break and Continue:

break [numeric expr];

continue [numeric expr];

Each accepts an optional numeric expressions representing the loop/switch nesting level to break/continue from, 1 being the nearest, loop/switch.

Return and Goto:

return [expr];

Returns from a function giving it its value, without expr return returns NULL;

Do not enclose expr in ()'s if you are returning a reference as ($a) != $a (($a) is just the value of $a, not its reference).

goto label;
...
label:

Moves execution to label.

Include and Require:

include "path";

Includes an external PHP source into the code at the point of the include.

require "path";

Like include, but produces an error if the include should fail.

include_once "path";
require_once "path";

Like include/require, but makes sure that the source is only included once, useful for when source files include source files that themselves include files that are commonly included by both.

Functions:

Like ECMAScript, functions are defined with the function keyword:

function foo($arg1, $arg2, ... , $argN) {
...
}

Add an ampersand (&) before an argument to use pass by reference rather than the default pass by value.

To return a reference prepend a ampersand (&) before the function name and when assigning the value. example:

function &ref() { return $ref; }
$newref =& ref();

Returning multiple values into multiple variables, use list():

function arr() { return Array(1,2,3); }
list($a,$b,$c) = arr();

Variable functions. Put the name of the function to be called in a variable then use the call () operator after the variable to call it:

$func = "foo";
$func();
$func(1, 2, etc);

  • Does not work for built-in functions.

Anonymous functions:

$func = function() { ... };