PHP cheatsheet
A cheatsheet for modern PHP (8.0+).
Variables
Variable variables
You can refer to a dynamic variable with $$. Probably avoid this feature.
$color = 'red';
$prop = 'color';
echo $$prop; // => red
echo ${$prop}; // => red
Variable scope
Variables in PHP have global and function scope. To refer to global variables in function scope, use the global keyword. A set of superglobal variables can be accessed in all scopes without using the global keyword.
PHP also has static variables that retain their value across function invocations. Their initialization is only executed on the first invocation, so they’re useful for caching the result of a computation, for example. When used in class methods, static variables are shared amongst all instances of the class and its subclasses.
Operators
The spaceship operator returns -1, 0, or 1 as a result of comparing its operands. Since comparison in PHP works with arrays, sorting by many criteria at once can be expressed succintly with:
usort(
$arr,
fn($a, $b) => [$a->title(), $a->date()] <=> [$b->title(), $b->date()]
);
False friends. The null coalescing operator ?? works similarly to JavaScript: a ?? b is equivalent to isset(a) ? a : b. However the boolean OR operator is unlike the Javascript counterpart: a || b returns a boolean, not either a or b. What you want instead is a ?: b, which is short for a ? a : b.
Strings
$name = 'Dan';
'My name is ' . $name; // Concatenation
"My name is $name"; // Interpolation
Arrays
Arrays in PHP are used for both indexed arrays and associative arrays (dictionaries), with support for int and string keys. String keys holding valid decimal integers will be interpreted as integers, unless the value starts with +.
$fruits = [];
$fruits[] = 'apple'; // Array push
The array push shortcut works for higher dimension arrays as well, creating the necessary objects as needed:
$tasks['Dan'][] = 'Documentation';
$transactions[$a][$b][] = $transaction;
Sorting arrays
sort()for sorting the values in indexed arrays;asort()for sorting the values in associative arrays;ksort()for sorting the keys in indexed and associative arrays;
To sort the array in descending order, use rsort(), arsort(), and krsort() respectively.
For custom sorting functions, there’s usort(), uasort(), and uksort() respectively.
Functions
Functions in PHP have surprising aspects coming from a JavaScript background. User-defined functions, regardless of the scope in which they were declared, are added to the global scope.
A function declaration, shown below with a default parameter value and a variable-length argument list:
function add($a, $b = 0, ...$rest) {
return $a + $b;
}
Functions can be invoked with positional arguments or named arguments (or combined):
add(5, 10); // positional arguments
add($b: 10, $a: 5); // named arguments
Arrays can be unpacked (spread) into arguments:
$numbers = [1, 2, 3];
add(...$numbers);
Anonymous functions or closures are defined with:
$add = function($a, $b) {
return $a + $b;
};
Variables from the outer scope are not available by default and must be explicitly inherited with use:
$padding = 10;
$add = function($a, $b) use ($padding) {
return $a + $b + $padding;
};
Variables inherited from the outer scope are passed by value. To pass by reference, you can use use(&$var).
$add = fn($a, $b) => $a + $b;
Arrow functions have implicit access to variables from the outer scope, roughly equivalent to use($var), so still passed by value. There’s no syntax for passing by reference in arrow functions, so you must use anonymous functions instead.
Classes
class MyClass {
const SOME_CONSTANT = 10;
public function __construct() {
}
}
Dates and times
Comparison and sorting
DateTime objects can be sorted with the spaceship operator:
$arr = [
new DateTime(…),
new DateTime(…),
new DateTime(…)
];
usort($arr, fn($a, $b) => $a <=> $b);
Timezones
The default timezone in PHP is UTC, but can be changed with the date_default_timezone_set() method or with the date.timezone configuration. To update the timezone for a DateTime object:
$date->setTimezone(new DateTimeZone('Europe/Bucharest'));
Internationalization
The intl extension provides locale-aware functions for collation, formatting numbers, dates, etc. On Homebrew it’s distributed separately from core PHP, so you’ll have to install it with:
brew install php php-intl
Type declarations
See Type declarations.
Use declare(strict_types=1); at the top of a PHP file to switch from PHPs default (coercive type checking) to strict type checking.
Development
Composer is the npm of the PHP world. On macOS I install Composer with Homebrew, which despite not being officially advertised seems mostly fine.
The most popular package repository is Packagist.
Miscellaneous
Write to built-in server stdout
Useful for local debugging.
define('STDOUT', fopen('php://stdout', 'w'));
fwrite(STDOUT, $str);
Further reading
- PHP cookbook, 4th ed.by Eric A. Mann (O’Reilly, 2023)
Tools, resources
- Laravel Herd is a local development environment