PHP

php.net

Scripting language intended for generating dynamic web pages






Building Blocks






Code

Only statements inside a block such as this are interpreted:

<?php
echo "Hello, world\n";
?>

Text outside the php delimiters is output by the interpreter unchanged.

Semicolons are used to separate statements. (Or, you can regard this as "statements must end with a semicolon".)






Comments

Anything following a // on a line is a comment.

Anything between /* and */ is a comment; this can spread over multiple lines.

 $x = 1;      // this is a comment
 /*
  These lines are
 a much longer
 comment
 */





Variables

A variable name consists of a $ followed by a series of alphanumeric characters; the first must be a letter or underscore. Names are case-sensitive.

Variables do not need to be declared. A variable is automatically created when a value is assigned to it.

 $x = 6;
 $y = $x * 9;
 $stringVariable27 = 'A string';





Numbers

Numbers can be integers or floating point. e.g.:

    1   
    -77777
    3.14159265
    1.5e+12





Strings

Text strings are normally enclosed in quotes (single or double).
Strings in single quotes are interpreted exactly as typed (except for \' and \\).
Strings in double quotes can include some formatting characters (e.g. \n for newline), and support parsing of variable names in the string - the variables' values are substituted into the string.

Multi-line strings can be created using the "heredoc syntax". heredoc strings support variable parsing like double-quoted strings.

    echo 'x';
    echo 'It\'s "its", not "it\'s"';
    echo "Hello, world\n";
    $str = <<<ENDSTRING
    Twas brillig and the slithy toves
    did gyre and gimble in the wabe.
    ENDSTRING;





Type conversion

PHP automatically converts values between strings and numbers as appropriate.

For example, the following will output 51:

  $x = "17";
  echo $x * 3;





Arrays

An array is a simple collection of data, such as a list.
They can grow to any size, without being fixed in advance.

In contrast to other languages, all arrays in PHP are actually associative arrays. A simple sequential list can be created by omitting the keys when creating or adding to an array - they will default to 0, 1, 2, ...

An array is created with the array() construct.

  $x = array('a', 'b', 'c');
  echo $x[2];

  $y = array('abc' => 1, 'd' => 99, 'xy' => -7);
  echo $y['abc'];

With an existing array, data can be added by assigning to a new entry. Leaving out the key (index by just []) will add to the end of the array.

  $y['o'] = 8;
  $x[] = 'd';





Operators

The standard mathematical operators ( + - * / ) exist for numbers.
As mentioned previously, strings will be automatically converted to numbers if you use them with a math operator.

String concatenation is done with the . operator.

  $x = 9;
  $y = ($x + 2) * 17;

  $a = 'abc';
  $b = $a . "def";





Comparison & logical operators

Logical operators are used for conditional expressions.
Similar to C, the numeric value 0 is equivalent to the logical value 'False', and non-0 is equivalent to 'True'.

|| Logical or
&& Logical and
! Logical negation
< <= > >= == != Numeric or string comparison





Code Blocks

Blocks of statements can be enclosed in curly-braces { }.
The first level of statements does not need to be in braces.
New levels are introduced by statements such as if, while, for, and foreach.

  if ($x > 5)
    {
    echo $x . "is greater than 5\n";
    }

  while ($x > 5)
    {
    if ($y <= 6)
        {
        echo $y . "\n";
        $y += 1;
        $x -= 1;
        }
    }





Assignment

The = operator performs assignment of values to variables

 $x = 7;
 $str = 'abc';





Conditionals

  if (1 > 2)
     echo "Something's wrong\n";

  if (($x > 3) && ($x < 4))
        {
        $y = $x;
        }
  elseif (x > 5)
        {
        $y = $x / 2;
        }
  else
        {
        $y = $x * 2;
        }





Iteration

while and for are used to perform actions in a loop

  for ($i=0; $i < 10; $i++)
     echo $i . "\n";

foreach is used to loop over elements of an array

  $arr = array('abc', 'def', 'ghi');
  foreach ($arr as $i)
    echo $i . "\n";

  $arr2 = array(1 => 'xyzzy', 4 => 'plugh');
  foreach ($arr2 as $k => $v)
    echo 'key ' . $k . ' has value ' . $v . "\n";





Functions

Functions are defined using the function statement.
They are called using the function name followed by parentheses, with any arguments inside the parentheses.

Function names follow the same rules as for variables, except that they do not start with $.

  function double($x)
        {
        echo $x * 2;
        }

  double(3);





Functions

A value can be returned from a function by the return statement.

  function factorial($n)
        {
        if ($n > 0)
                return $n * factorial($n-1);
        else
                return 1;
        }
  
  $x = factorial(5);





Variable Scoping

By default, variables that are assigned to in a function only exist within that function - i.e. they have local scope.

The global statement declares that a variable has global scope.
This will make it visible outside of the function, after the function has been called.
It also allows you to use variables already defined in the global scope.

The following example will output "12".

  function foo($a)
    {
    global $y;
    $y = $a;
    }
  foo(12);
  echo $y;





Includes

The include and require commands allow you to load code that is in a separate PHP file.



Creative Commons License
This document is by Dave Pape, and is released under a Creative Commons License.