0% found this document useful (0 votes)
438 views

PHP Cheat Sheet

This document is a cheat sheet for PHP that provides code examples and explanations of key PHP concepts like variables, data types, strings, arrays, functions, loops, classes and more in a condensed format.

Uploaded by

Pas DEN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
438 views

PHP Cheat Sheet

This document is a cheat sheet for PHP that provides code examples and explanations of key PHP concepts like variables, data types, strings, arrays, functions, loops, classes and more in a condensed format.

Uploaded by

Pas DEN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

PHP Cheat Sheet

Hello World Integers Anonymous Functions (Closures)


Example Value
<?php $y = 3;
echo 'Hello, World!'; 28 28 $foo = function(int $x) use ($y): int {
return $x + $y;
10_000 (PHP 7.4) 10000
};
PHP Tags -28 -28 $foo(1); // 4
Tag Description
012 10 (octal)
<?php Standard opening tag
0x0A 10 (hexadecimal)
Arrow Functions (PHP 7.4)
<? Short opening tag
0b1010 10 (binary) $y = 3;
<?= $foo Short opening tag with echo $foo = fn(int $x): int => $x + $y;
$foo(1); // 4
?> Standard closing tag
Floats
Example Value Generators
Variables 1.234 1.234
function generate(): iterable
$greeting = 'Hello, World!'; -1.2 -1.2 {
echo $greeting; // Hello, World! yield 1;
1.2e3 1200 (scientific notation)
yield 2;
}
Constants 7E-3 0.007 (scientific notation)

const CONSTANT = 'value'; foreach (generate() as $value) {


define('RUNTIME_CONSTANT', CONSTANT); Arrays echo $value;
}
$array = [1, 2, 3];
echo CONSTANT; // value
$array[] = 4;
echo RUNTIME_CONSTANT; // value
$array[4] = 5; Comments
// This is a one line C++ style comment
Strings Functions # This is a one line shell-style comment
$name = 'World'; /* This is a
function foo(int $a, int $b = 5): int multi-line comment */
echo 'Hello, $name!'; // Hello, $name!
{
echo "Hello, $name!"; // Hello, World!
return $a + $b; /**
echo "Hello, {$name}!"; // Hello, World!
} * This is a PHPDoc docblock
foo(1, 2); // 3 * @param string[] $bar
echo <<<END
foo(1); // 6 * @return void
This is a multi-line string
in HEREDOC syntax (with interpolation). */
END; Named Parameters (PHP 8.0) function foo(array $bar): void
{}
echo <<<'END' function foo(int $a, int $b): int
This is a multi-line string {
return $a + $b;
Attributes (PHP 8.0)
in NOWDOC syntax (without interpolation).
END; } #[Foo(bar: 'baz')]
foo(b: 2, a: 1); class Bar {}

© Nic Wortel, Software Consultant & Trainer - Updated for PHP 8.3 - Last updated on January 17, 2024 - Find more cheat sheets at https://nicwortel.nl/cheat-sheets
Atomic / Built-in Types While Enumerations (PHP 8.1)
Type Description
while ($i < 10) { enum Suit {
null NULL (no value) echo $i++; case Hearts;
} case Diamonds;
bool Boolean (true or false)
case Clubs;
int Integer case Spades;
Do/While }
float Floating point number
do {
string String echo $i++; $suit = Suit::Hearts;
} while ($i < 10); $suit->name; // Hearts
array Array
object Object
For Backed Enumerations (PHP 8.1)
resource Reference to an external resource
for ($i = 0; $i < 10; $i++) { enum Suit: string {
callable Callback function case Hearts = '♥';
echo $i;
void Function does not return a value } case Diamonds = '♦';
case Clubs = '♣';
never (PHP 8.1) Function never terminates case Spades = '♠';
false (PHP 8.0) false Foreach }

true (PHP 8.2) true foreach ($array as $value) { $hearts = Suit::from('♥');


echo $value; $hearts->value; // '♥'
}
Composite Types & Type Aliases
Type Description foreach ($array as $key => $value) { Language Constructs
echo "$key: $value"; Construct Description
?string Nullable type: string or null }
echo $string Output one or more strings
string|bool (PHP 8.0) Union type: string or bool
Foo&Bar (PHP 8.1) Intersection type: Foo and Bar Switch print $string Output a string and return 1
unset($var) Destroy the specified variable(s)
(A&B)|null (PHP 8.2) Disjunctive Normal Form (DNF) switch ($i) {
case 0: isset($var) Determine if a variable is set
iterable array or Traversable
case 1:
empty($var) Determine if a variable is empty
mixed (PHP 8.0) Any type echo "i equals 0 or 1";
break; die() Output a message and terminate
default:
If/Else echo "i is not equal to 0 or 1";
exit() Output a message and terminate

} Include and evaluate a file or


if ($a > $b) { include <file>
throw a warning if it fails
echo "a is greater than b";
} elseif ($a == $b) { Match (PHP 8.0) require <file>
Include and evaluate a file or
echo "a is equal to b"; throw an error if it fails
} else { $foo = match ($i) { Include and evaluate a file once
echo "a is less than b"; 0 => "i equals 0", include_once <file>
only or throw a warning if it fails
} 1, 2 => "i equals 1 or 2",
default => "i is not equal to 0, 1 or 2", Include and evaluate a file once
require_once <file>
}; only or throw an error if it fails

© Nic Wortel, Software Consultant & Trainer - Updated for PHP 8.3 - Last updated on January 17, 2024 - Find more cheat sheets at https://nicwortel.nl/cheat-sheets
Object-Oriented Programming Property Keywords Namespacing and Importing
Keyword Description
interface FooInterface namespace Foo\Bar;
{ Can be accessed statically (e.g.
static
public function baz(): string; Foo::$bar) use Foo\Baz as BazAlias;
} use Foo\Baz\{Qux, Quux};
readonly (PHP 8.1) Can only be set in the constructor
use function strlen;
class Foo extends Bar implements FooInterface
{ Constructor Property Promotion Exceptions
private string $bar;
class Foo try {
public const string BAZ = 'Hello, '; { throw new Exception('Something went wrong');
public function __construct(private string $bar) } catch (Exception $e) {
public function __construct(string $bar) { // Code that runs when an exception is thrown
{ } } finally {
$this->bar = $bar; } // Code that will always run
} }

public function baz(): string Method keywords


{ Keyword Description Traits
return self::BAZ . $this->bar;
Can be called statically (e.g. trait FooTrait
} static
Foo::bar()) {
}
Must be implemented by public function baz(): string
abstract {}
$foo = new Foo("World!"); subclasses
echo $foo->baz(); // Hello, World!' }
Cannot be overridden by
echo Foo::BAZ; // Hello, final
subclasses
class Foo
{
Class Keywords Predefined attributes use FooTrait;
Keyword Description }
Attribute Description
Class has abstract methods and
abstract
cannot be instantiated
#[Attribute] User-defined attribute class Magic Methods
#[SensitiveParameter] Parameter contains sensitive data Method Called when...
final Class cannot be extended
#[AllowDynamicProperties] Class allows dynamic properties __construct(...$args) Object is instantiated (constructor)
extends <class> Class extends another class
#[Override] (PHP 8.3) Method overrides parent method __destruct() Object is destroyed
implements <interface> Class implements an interface
__toString() Object is converted to a string
readonly (PHP 8.2) All properties are read-only
Calling Methods/Properties/Constants __invoke(...$args) Object is used as a function
Syntax Calls foo() on... __get($name) Undefined property is accessed
Method/Property/Constant Visibility
$this->foo() The current object ($this) __set($name, $value) Undefined property is set
Keyword Description
Foo::foo() The class named Foo __isset($name) Undefined property is checked
public Accessible from anywhere
self::foo() The current class __unset($name) Undefined property is unset
Accessible from the class and
protected parent::foo() The parent (extended) class
subclasses __call($name, $args) Undefined method is called

private Accessible from the class only static::foo() The called class (late static binding) __clone() Object is cloned (clone $obj)

© Nic Wortel, Software Consultant & Trainer - Updated for PHP 8.3 - Last updated on January 17, 2024 - Find more cheat sheets at https://nicwortel.nl/cheat-sheets
Arithmetic Operators Comparison Operators String Operators
Operator Description Operator Description Operator Description
+ Addition == Equal (values are converted) . Concatenate
- Subtraction Identical (values and types .= Concatenate and assign
===
match)
* Multiplication
!= Not equal
/ Division Other Operators
<> Not equal Operator Description
% Modulus
!== Not identical Ternary operator: return $b if $a
** Exponentiation $a ? $b : $c
< Less than is true, otherwise return $c

> Greater than Short ternary: return $a if $a is


Bitwise Operators $a ?: $b
true, otherwise return $b
Operator Description <= Less than or equal to
Null coalescing: return $a if $a is
$a ?? $b
& And >= Greater than or equal to not null, otherwise return $b

| Or (inclusive) Returns -1, 0, or 1 if the first Null coalescing assignment:


$a ??= $b
<=> value is less than, equal to, or assign $b to $a if $a is null
^ Xor (exclusive) greater than the second value
Nullsafe: return $a->b if $a is not
$a?->b
~ Not null, otherwise return null
<< Shift left Incrementing/Decrementing Operators $a = &$b Assign $b by reference to $a
>> Shift right Operator Description Suppress errors in the following
@
Increments $a by one, then expression
++$a
returns $a Returns true if the left operand is
Assignment Operators instanceof
an instance of the right operand
Returns $a, then increments $a
Operator Description $a++
by one
= Assign
--$a
Decrements $a by one, then Command Line Interface (CLI)
+= Add and assign returns $a
Command Description
-= Subtract and assign Returns $a, then decrements $a
$a-- php <file> Parse and execute <file>
by one
*= Multiply and assign php -l <file> Syntax check <file>
/= Divide and assign
Logical Operators php -r <code>
Run PHP <code> without using
%= Modulus and assign script tags
Operator Description
**= Exponent and assign php -a Run an interactive shell
and And
&= Bitwise and and assign php -S <addr>:<port> Start built-in web server
or Or
|= Bitwise or and assign php -S <addr>:<port> -t Start built-in web server and
xor Exclusive or <dir> specify document root
^= Bitwise xor and assign ! Not php -m Show loaded modules
<<= Bitwise shift left and assign && And php -i Show configuration information
>>= Bitwise shift right and assign || Or php -v Show PHP version
php -h Show help

© Nic Wortel, Software Consultant & Trainer - Updated for PHP 8.3 - Last updated on January 17, 2024 - Find more cheat sheets at https://nicwortel.nl/cheat-sheets
String Functions Array Functions Filesystem Functions
Function Description Function Description Function Description

strlen($string) Return length of $string Return number of elements in file_exists($filename) Return true if $filename exists
count($array)
$array
str_replace($search, Replace $search with $replace Return true if $filename is a
is_dir($filename)
$replace, $subject) in $subject sort($array) Sort $array directory

strstr($haystack, Return part of $haystack after array_merge($array1, Return true if $filename is a


Merge $array1 and $array2 is_file($filename)
$needle) $needle $array2) regular file

substr($string, $start, Return part of $string starting array_map($callback, Apply $callback to each Return true if $filename is
is_readable($filename)
readable
$length) at $start $array) element of $array
Return true if $filename is
strtolower($string) Return $string in lowercase array_filter($array, Return elements of $array for is_writable($filename)
writable
$callback) which $callback returns true
strtoupper($string) Return $string in uppercase Create directory named
Reduce $array to a single value mkdir($pathname)
Return $string with whitespace array_reduce($array, $pathname
trim($string) using $callback starting with
trimmed $callback, $initial)
$initial Remove directory named
rmdir($dirname)
Return $string with left $dirname
ltrim($string) Return part of $array starting at
whitespace trimmed array_slice($array, unlink($filename) Remove file named $filename
$offset and continuing for
$offset, $length)
Return $string with right $length elements
rtrim($string) file_get_contents($filename) Return contents of $filename
whitespace trimmed Return an array of keys from
array_keys($array) file_put_contents($filename,
$array Write $data to $filename
explode($delimiter, Split $string into an array by $data)
$string) $delimiter Return an array of values from
array_values($array)
Join $array into a string with $array
implode($glue, $array)
$glue
php.ini Directives
array_combine($keys, Return an array of key/value pairs
$values) from $keys and $values Directive Description
str_repeat($string, Repeat $string $multiplier
$multiplier) times date.timezone Set default timezone
Return a reversed copy of
array_reverse($array)
$array Set error reporting level (e.g.
error_reporting
E_ALL, E_ERROR)
Math Functions array_search($needle, Return the key of $needle in
$haystack) $haystack Whether to display errors (e.g. On
Function Description display_errors
or Off)
Return a copy of $array with
abs($num) Return absolute value of $num array_unique($array)
duplicate values removed Set error log file (e.g.
error_log
Round $num to the nearest /var/log/php.log)
round($num) array_diff($array1, Return elements of $array1 not
integer $array2) in $array2 Mode (e.g. debug, develop,
xdebug.mode
ceil($num) Round $num up profile)
array_intersect($array1, Return elements of $array1 also
floor($num) Round $num down $array2) in $array2 Enable Xdebug to discover client
xdebug.discover_client_host
host automatically
max($a, $b) Return the greater of $a and $b
min($a, $b) Return the lesser of $a and $b
Date/Time Functions
Enable Xdebug Step Debugging
Function Description
Return $a raised to the power of
pow($a, $b) XDEBUG_MODE=debug XDEBUG_SESSION=1 php <file>
$b Return current date/time
date($format)
formatted according to $format
Return a random number between Or for web applications using a browser extension: Firefox Helper
rand($min, $max)
$min and $max time() Return current Unix timestamp Chrome Helper
sqrt($num) Return square root of $num

© Nic Wortel, Software Consultant & Trainer - Updated for PHP 8.3 - Last updated on January 17, 2024 - Find more cheat sheets at https://nicwortel.nl/cheat-sheets

You might also like