
PHP Cheat Sheet
This PHP cheat sheet provides a reference for quickly looking up the correct syntax for the code you use most
Miscellaneous
Runtime defined Constants
define("CURRENT\_DATE", date('Y-m-d')); // One possible representation echo CURRENT_DATE; # => 2021-01-05 # => CURRENT\_DATE is: 2021-01-05 echo 'CURRENT\_DATE is: ' . CURRENT_DATE;
fopen() mode
- | - |
---|---|
r | Read |
r+ | Read and write, prepend |
w | Write, truncate |
w+ | Read and write, truncate |
a | Write, append |
a+ | Read and write, append |
Regular expressions
$str = "Visit Quickref.me"; echo preg\_match("/qu/i", $str); # => 1
See: Regex in PHP
Nullsafe Operator
// As of PHP 8.0.0, this line: $result = $repo?->getUser(5)?->name; // Equivalent to the following code: if (is\_null($repo)) { $result = null; } else { $user = $repository->getUser(5); if (is\_null($user)) { $result = null; } else { $result = $user->name; } }
See also: Nullsafe Operator
Custom exception
class MyException extends Exception { // do something }
Usage
try { $condition = true; if ($condition) { throw new MyException('bala'); } } catch (MyException $e) { // Handle my exception }
Exception in PHP 8.0
$nullableValue = null; try { $value = $nullableValue ?? throw new InvalidArgumentException(); } catch (InvalidArgumentException) { // Variable is optional // Handle my exception echo "print me!"; }
Basic error handling
try { // Do something } catch (Exception $e) { // Handle exception } finally { echo "Always print!"; }
PHP Classes
Interface
interface Foo { public function doSomething(); } interface Bar { public function doSomethingElse(); } class Cls implements Foo, Bar { public function doSomething() {} public function doSomethingElse() {} }
Magic Methods
class MyClass { // Object is treated as a String public function \_\_toString() { return $property; } // opposite to \_\_construct() public function \_\_destruct() { print "Destroying"; } }
Classes variables
class MyClass { const MY\_CONST = 'value'; static $staticVar = 'static'; // Visibility public static $var1 = 'pubs'; // Class only private static $var2 = 'pris'; // The class and subclasses protected static $var3 = 'pros'; // The class and subclasses protected $var6 = 'pro'; // The class only private $var7 = 'pri'; }
Access statically
echo MyClass::MY\_CONST; # => value echo MyClass::$staticVar; # => static
Inheritance
class ExtendClass extends SimpleClass { // Redefine the parent method function displayVar() { echo "Extending class\n"; parent::displayVar(); } } $extended = new ExtendClass(); $extended->displayVar();
Constructor
class Student { public function \_\_construct($name) { $this->name = $name; } public function print() { echo "Name: " . $this->name; } } $alex = new Student("Alex"); $alex->print(); # => Name: Alex
PHP Functions
Arrow Functions
$y = 1; $fn1 = fn($x) => $x + $y; // equivalent to using $y by value: $fn2 = function ($x) use ($y) { return $x + $y; }; echo $fn1(5); # => 6 echo $fn2(5); # => 6
Default parameters
function coffee($type = "cappuccino") { return "Making a cup of $type.\n"; } # => Making a cup of cappuccino. echo coffee(); # => Making a cup of . echo coffee(null); # => Making a cup of espresso. echo coffee("espresso");
Recursive functions
function recursion($x) { if ($x < 5) { echo "$x"; recursion($x + 1); } } recursion(1); # => 1234
Anonymous functions
$greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); # => Hello World $greet('PHP'); # => Hello PHP
Variable functions
function bar($arg = '') { echo "In bar(); arg: '$arg'.\n"; } $func = 'bar'; $func('test'); # => In bar(); arg: test
Void functions
// Available in PHP 7.1 function voidFunction(): void { echo 'Hello'; return; } voidFunction(); # => Hello
Nullable return types
// Available in PHP 7.1 function nullOrString(int $v) : ?string { return $v % 2 ? "odd" : null; } echo nullOrString(3); # => odd var\_dump(nullOrString(4)); # => NULL
See: Nullable types
Return types
// Basic return type declaration function sum($a, $b): float {/\*...\*/} function get\_item(): string {/\*...\*/} class C {} // Returning an object function getC(): C { return new C; }
Returning values
function square($x) { return $x * $x; } echo square(4); # => 16
PHP Loops
foreach
$a = ['foo' => 1, 'bar' => 2]; # => 12 foreach ($a as $k) { echo $k; }
See: Array iteration
continue
# => 1235 for ($i = 1; $i <= 5; $i++) { if ($i === 4) { continue; } echo $i; }
break
# => 123 for ($i = 1; $i <= 5; $i++) { if ($i === 4) { break; } echo $i; }
for i
# => 12345 for ($i = 1; $i <= 5; $i++) { echo $i; }
do while
$i = 1; # => 12345 do { echo $i++; } while ($i <= 5);
while
$i = 1; # => 12345 while ($i <= 5) { echo $i++; }
PHP Conditionals
Match expressions
$age = 23; $result = match (true) { $age >= 65 => 'senior', $age >= 25 => 'adult', $age >= 18 => 'young adult', default => 'kid', }; echo $result; # => young adult
Ternary operator
# => Does print (false ? 'Not' : 'Does'); $x = false; # => Does print($x ?: 'Does'); $a = null; $b = 'Does print'; # => a is unset echo $a ?? 'a is unset'; # => print echo $b ?? 'b is unset';
Switch
$x = 0; switch ($x) { case '0': print "it's zero"; break; case 'two': case 'three': // do something break; default: // do something }
If elseif else
$a = 10; $b = 20; if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; }
PHP Operators
Bitwise
- | - |
---|---|
& | And |
| | Or (inclusive or) |
^ | Xor (exclusive or) |
~ | Not |
<< | Shift left |
>> | Shift right |
Logical
- | - |
---|---|
and | And |
or | Or |
xor | Exclusive or |
! | Not |
&& | And |
|| | Or |
Comparison
- | - |
---|---|
== | Equal |
=== | Identical |
!= | Not equal |
<> | Not equal |
!== | Not identical |
< | Less than |
> | Greater than |
<= | Less than or equal |
>= | Greater than or equal |
<=> | Less than/equal/greater than |
Assignment
- | - |
---|---|
a += b | Same as a = a + b |
a -= b | Same as a = a â b |
a *= b | Same as a = a * b |
a /= b | Same as a = a / b |
a %= b | Same as a = a % b |
Arithmetic
- | - |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo |
** | Exponentiation |
PHP Arrays
Splat Operator
function foo($first, ...$other) { var\_dump($first); # => a var\_dump($other); # => ['b', 'c'] } foo('a', 'b', 'c' /\*, ...\*/ ); // or function foo($first, string ...$other){}
Into functions
$array = [1, 2]; function foo(int $a, int $b) { echo $a; # => 1 echo $b; # => 2 } foo(...$array);
Concatenate arrays
$a = [1, 2]; $b = [3, 4]; // PHP 7.4 later # => [1, 2, 3, 4] $result = [...$a, ...$b];
Key iteration
$arr = ["foo" => "bar", "bar" => "foo"]; foreach ( $arr as $key => $value ) { echo "key: " . $key . "\n"; echo "val: {$arr[$key]}\n"; }
Value iteration
$colors = array('red', 'blue', 'green'); foreach ($colors as $color) { echo "Do you like $color?\n"; }
Indexing iteration
$array = array('a', 'b', 'c'); $count = count($array); for ($i = 0; $i < $count; $i++) { echo "i:{$i}, v:{$array[$i]}\n"; }
Multi type
$array = array( "foo" => "bar", 42 => 24, "multi" => array( "dim" => array( "a" => "foo" ) ) ); # => string(3) "bar" var\_dump($array["foo"]); # => int(24) var\_dump($array[42]); # => string(3) "foo" var\_dump($array["multi"]["dim"]["a"]);
Multi array
$multiArray = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; print\_r($multiArray[0][0]) # => 1 print\_r($multiArray[0][1]) # => 2 print\_r($multiArray[0][2]) # => 3
PHP Strings
Manipulation
$s = "Hello Phper"; echo strlen($s); # => 11 echo substr($s, 0, 3); # => Hel echo substr($s, 1); # => ello Phper echo substr($s, -4, 3);# => hpe echo strtoupper($s); # => HELLO PHPER echo strtolower($s); # => hello phper echo strpos($s, "l"); # => 2 var\_dump(strpos($s, "L")); # => false
See: String Functions
Multi-line
$str = "foo"; // Uninterpolated multi-liners $nowdoc = <<<'END' Multi line string $str END; // Will do string interpolation $heredoc = <<<END Multi line $str END;
String
# => '$String' $sgl\_quotes = '$String'; # => 'This is a $String.' $dbl\_quotes = "This is a $sgl\_quotes."; # => a tab character. $escaped = "a \t tab character."; # => a slash and a t: \t $unescaped = 'a slash and a t: \t';
PHP Types
Iterables
function bar(): iterable { return [1, 2, 3]; } function gen(): iterable { yield 1; yield 2; yield 3; } foreach (bar() as $value) { echo $value; # => 123 }
Null
$a = null; $b = 'Hello php!'; echo $a ?? 'a is unset'; # => a is unset echo $b ?? 'b is unset'; # => Hello php $a = array(); $a == null # => true $a === null # => false is\_null($a) # => false
Float (Double)
$float1 = 1.234; $float2 = 1.2e7; $float3 = 7E-10; $float4 = 1\_234.567; // as of PHP 7.4.0 var\_dump($float4); // float(1234.567) $float5 = 1 + "10.5"; # => 11.5 $float6 = 1 + "-1.3e3"; # => -1299
Boolean
$boolean1 = true; $boolean2 = TRUE; $boolean3 = false; $boolean4 = FALSE; $boolean5 = (boolean) 1; # => true $boolean6 = (boolean) 0; # => false
Boolean are case-insensitive
Getting Started
Constants
const MY\_CONST = "hello"; echo MY_CONST; # => hello # => MY\_CONST is: hello echo 'MY\_CONST is: ' . MY_CONST;
Comments
# This is a one line shell-style comment // This is a one line c++ style comment /\* This is a multi line comment yet another line of comment \*/
Include
#vars.php
<?php // begin with a PHP open tag. $fruit = 'apple'; echo "I was imported"; return 'Anything you like.'; ?>
#test.php
<?php include 'vars.php'; echo $fruit . "\n"; # => apple /\* Same as include, cause an error if cannot be included\*/ require 'vars.php'; // Also works include('vars.php'); require('vars.php'); // Include through HTTP include 'http://x.com/file.php'; // Include and the return statement $result = include 'vars.php'; echo $result; # => Anything you like. ?>
hello.php
<?php // begin with a PHP open tag. echo "Hello World\n"; print("Hello quickref.me"); ?>
PHP run command
$ php hello.php