The PHP engine only interprets PHP code that is found within <?php ... ?> sections. Everything else is just "printed/transmitted" as normal text (called "output".)
<?php
?>
<?php echo "Hello, again!"; ?>
<?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"; ?>
$x = true; $x = false;
$x = 123; // Decimal $x = 0xff; // Hexadecimal $x = 0777; // Octal
(int)
$x = (int)"123";
$x = 1.25; $x = 10E+5; // Exponential form
cast (float) to convert to floating-point.
(float)
is_nan($x) to test if a number or not.
is_nan($x)
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 ` ;
$x =
;
(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
Simple syntax:
".. $name ..", "...${name}abc" ".. $name[0] ..", ".. $name[key] .."
".. $name ..", "...${name}abc"
".. $name[0] ..", ".. $name[key] .."
Complex syntax:
"..{$vardesc}..": "..{$name[0][1]}.." "..{$name['key']}.." "..{$class->method()}.."
"..{$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.
strlen($str)
explode($sep, $str [,$limit])
ltrim($str [,$chars])
rtrim($str [,$chars])
trim($str [,$chars])
To convert a different type to a string, use a (string) cast or the strval() function.
(string)
strval()
$x = 10; $s = (string)$n;
$x = 10;
$s = (string)$n;
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']
$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
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.
sizeof
The list() operator allows one to assign the values of an array to individual variables in one assignment:
list()
list($var1, $var2, ... $varN) = array $value;
<?php $foo = array("Bob", "Smith", 45); list($fname, $lname, $age) = $foo; ?>
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"; ?>
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;
Used for things like file descriptors, or network handles or pointers to functions.
Defined with:
define(string $name, mixed $value [,bool $case_insensitive=false])
define(
$name,
$value [,
$case_insensitive=false])
mixed = (boolean, integer, float and string), array added in PHP7.
boolean
integer
float
string
array
Constants have super global scope.
Inside classes, to declare a constant, use:
const name = value;
const
=
define() does not work inside of classes.
define()
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
$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV
$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)
$a ** $b
$a == $b
$a === $b
$a <> $b
$a !== $b
$a <=> $b
Prepend @ to almost anything that can give a value and PHP will ignore any errors that it might produce. (sets logging level to 0?)
@
<?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; ?>
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>"; ?>
and, or and xor in addition to &&, || and !
and
or
xor
&&
||
!
examples:
$foo = $a and $b; $bar = $a xor $b;
$foo = $a and $b;
$bar = $a xor $b;
.
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";
"abc" . "def"
"abcdef"
$x .= "abc";
$x = $x . "abc";
$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
$a + $b
$a != $b
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.:
{
:
}
end
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.
endif;
<?php if (expr): echo "..."; else { echo "..."; } ?>
if ( expr ) statement [else if ( expr ) statement] [elseif ( expr ) statement] [else statement]
if (
)
[else if (
]
[elseif (
[else
or alt syntax (note: no 'else if:')
else if:
if ( expr ): [elseif ( expr ):] [else:] endif;
):
):]
[else:]
switch( expr ) { [case constant:] [default:] }
switch(
) {
[case
:]
[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;"
continue
break
continue 2;
Alternate syntax:
switch( expr ): [case const:] [default:] endswitch;
endswitch;
There can be no output between the switch(expr): line and first case.
while ( expr ) statement
while (
or:
while ( expr ): ...statements endwhile;
endwhile;
do statement while( expr );
do
while(
);
for(init-expr; test-expr; inc-expr ) statement
for(
for(init-expr; test-expr; inc-expr ): ...statements endfor;
endfor;
foreach(array_expr as $value ) statement
foreach(
as
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.
unset($value);
Functionally equivalent to:
reset($array); while(list(,$value) = each($array)) statement;
reset($array);
while(list(,$value) = each($array)) statement;
while(list($key, $value) = each($array)) statement;
break [numeric expr];
break [
];
continue [numeric expr];
continue [
Each accepts an optional numeric expressions representing the loop/switch nesting level to break/continue from, 1 being the nearest, loop/switch.
return [expr];
return [
Returns from a function giving it its value, without expr return returns NULL;
return
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).
($a) != $a
goto label; ... label:
goto
Moves execution to label.
include "path";
include "
";
Includes an external PHP source into the code at the point of the include.
require "path";
require "
Like include, but produces an error if the include should fail.
include
include_once "path"; require_once "path";
include_once "
require_once "
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.
require
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();
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();
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);
$func = "foo";
$func();
$func(1, 2, etc);
Anonymous functions:
$func = function() { ... };