PHP Cheat Sheet & Quick Reference
PHP Cheat Sheet & Quick Reference
This PHP cheat sheet provides a reference for quickly looking up the correct syntax for the code you use most frequently.
# Getting Started
hello.php
?>
PHP run command
$ php hello.php
Variables
$boolean1 = true;
$boolean2 = True;
$int = 12;
$float = 3.1415926;
unset($float); // Delete variable
Strings
$url = "quickref.me";
echo "I'm learning PHP at $url";
// Concatenate strings
echo "I'm learning PHP at " . $url;
See: Strings
Arrays
See: Arrays
Operators
$x = 1;
$y = 2;
$sum = $x + $y;
echo $sum; # => 3
See: Operators
Include
vars.php
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';
See: Functions
Comments
Constants
class Student {
public function __construct($name) {
$this->name = $name;
}
}
$alex = new Student("Alex");
See: Classes
# PHP Types
Boolean
$boolean1 = true;
$boolean2 = TRUE;
$boolean3 = false;
$boolean4 = FALSE;
Integer
$int1 = 28; # => 28
$int2 = -32; # => -32
$int3 = 012; # => 10 (octal)
$int4 = 0x0F; # => 15 (hex)
$int5 = 0b101; # => 5 (binary)
Strings
See: Strings
Arrays
See: Arrays
Float (Double)
$float1 = 1.234;
$float2 = 1.2e7;
$float3 = 7E-10;
$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
Iterables
# => '$String'
$sgl_quotes = '$String';
Multi-line
$str = "foo";
// Uninterpolated multi-liners
$nowdoc = <<<'END'
Multi line string
$str
END;
$s = "Hello Phper";
echo strlen($s); # => 11
# PHP Arrays
Defining
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
d ($ )
Short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
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
Multi type
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dim" => array(
"a" => "foo"
)
)
);
# => int(24)
var_dump($array[42]);
manipulation
Indexing iteration
Key iteration
Concatenate arrays
$a = [1, 2];
$b = [3, 4];
Into functions
Splat Operator
# PHP Operators
Arithmetic
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
** Exponentiation
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
Comparison
== Equal
=== Identical
!= Not equal
Logical
and And
or Or
xor Exclusive or
! Not
&& And
|| Or
Arithmetic
// Arithmetic
$sum = 1 + 1; // 2
$difference = 2 - 1; // 1
$product = 2 * 2; // 4
$quotient = 2 / 1; // 2
// Shorthand arithmetic
$num = 0;
$num += 1; // Increment $num by 1
echo $num++; // Prints 1 (increments after evaluation)
echo ++$num; // Prints 3 (increments before evaluation)
$num /= $float; // Divide and assign the quotient to $num
Bitwise
& And
| Or (inclusive or)
# PHP Conditionals
If elseif else
$a = 10;
$b = 20;
Switch
$x = 0;
switch ($x) {
case '0':
print "it's zero";
break;
case 'two':
case 'three':
// do something
break;
default:
// do something
}
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';
Match
$statusCode = 500;
$message = match($statusCode) {
200, 300 => null,
400 => 'not found',
500 => 'server error',
default => 'known status code',
};
See: Match
Match expressions
$age = 23;
# PHP Loops
while
$i = 1;
# => 12345
while ($i <= 5) {
echo $i++;
}
do while
$i = 1;
# => 12345
do {
echo $i++;
} while ($i <= 5);
for i
# => 12345
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
break
# => 123
for ($i = 1; $i <= 5; $i++) {
if ($i === 4) {
break;
}
echo $i;
}
continue
# => 1235
for ($i = 1; $i <= 5; $i++) {
if ($i === 4) {
continue;
}
foreach
# PHP Functions
Returning values
function square($x)
{
return $x * $x;
}
Return types
Void functions
Variable functions
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
Recursive functions
function recursion($x)
{
if ($x < 5) {
echo "$x";
recursion($x + 1);
}
}
recursion(1); # => 1234
Default parameters
Arrow Functions
$y = 1;
# PHP Classes
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
Inheritance
Classes variables
class MyClass
{
const MY_CONST = 'value';
static $staticVar = 'static';
// Visibility
public static $var1 = 'pubs';
// Class only
private static $var2 = 'pris';
Access statically
Magic Methods
class MyClass
{
// Object is treated as a String
public function __toString()
{
return $property;
}
// opposite to __construct()
public function __destruct()
{
print "Destroying";
}
}
Interface
interface Foo
{
public function doSomething();
}
interface Bar
{
public function doSomethingElse();
}
class Cls implements Foo, Bar
{
public function doSomething() {}
public function doSomethingElse() {}
}
# Miscellaneous
Basic error handling
try {
// Do something
} catch (Exception $e) {
// Handle exception
} finally {
echo "Always print!";
}
$nullableValue = null;
try {
$value = $nullableValue ?? throw new InvalidArgumentException();
} catch (InvalidArgumentException) { // Variable is optional
// Handle my exception
echo "print me!";
}
Custom exception
Usage
try {
$condition = true;
if ($condition) {
throw new MyException('bala');
}
} catch (MyException $e) {
// Handle my exception
}
Nullsafe Operator
Regular expressions
fopen() mode
r Read
w Write, truncate
a Write, append