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

PHP Cheat Sheet

Uploaded by

Clarisse Gatuz
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)
89 views

PHP Cheat Sheet

Uploaded by

Clarisse Gatuz
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 10000
};
PHP Tags -28 -28 $foo(1); // 4
Tag Description
012 10 (octal)
<?php Standard opening tag
0x0A 10 (hexadecimal)
Arrow Functions
<?= $foo Short echo tag
0b1010 10 (binary) $y = 3;
<? Short opening tag (discouraged) $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 function foo(array $bar): void
{}
echo <<<'END' function foo(string $a, string $b): string
This is a multi-line string {
in NOWDOC syntax (without interpolation). return $a . $b;
END; }
foo(b: 'World!', a: 'Hello, '); // Hello, World!

© Nic Wortel, Software Consultant & Trainer - Updated for PHP 8.4 - Last updated on November 6, 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 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 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 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 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.4 - Last updated on November 6, 2024 - Find more cheat sheets at https://nicwortel.nl/cheat-sheets
Object-Oriented Programming Property Keywords Calling Methods/Properties/Constants
Keyword Description Syntax Calls foo() on...
interface FooInterface
{ static Can be accessed statically $foo->foo() The object referenced by $foo
public function baz(): string;
readonly (PHP 8.1) Can only be set in the constructor $this->foo() The current object ($this)
}
Foo::foo() The class Foo
class Foo extends Bar implements FooInterface
Method/Property/Constant Visibility self::foo() The current class
{
private string $bar; Keyword Accessible from parent::foo() The parent (extended) class
public Anywhere static::foo() The called class
public const string BAZ = 'Hello, ';
protected The current class and subclasses
public function __construct(string $bar) private The current class only Namespacing and Importing
{
$this->bar = $bar; namespace Foo\Bar;
} Constructor Property Promotion
use Foo\Baz as BazAlias;
public function baz(): string class Foo use Foo\Baz\{Qux, Quux};
{ { use function strlen;
return self::BAZ . $this->bar; public function __construct(private string $bar) use const PHP_EOL;
} {}
} }
Exceptions
$foo = new Foo("World!");
Property Hooks (PHP 8.4) try {
echo $foo->baz(); // Hello, World!'
throw new Exception('Something went wrong');
echo Foo::BAZ; // Hello, class Foo } catch (Exception $e) {
{ // Code that runs when an exception is thrown
Class Keywords public string $name { } finally {
// (string $value) can be omitted // Code that will always run
Keyword Description set (string $value) { }
abstract Cannot be instantiated $this->name = strtolower($value);
}
final Cannot be extended // Short (closure-style) syntax Traits
extends Extends another class get => ucfirst($this->name);
} trait FooTrait
implements Implements an interface } {
public function baz(): string { ... }
readonly (PHP 8.2) All properties are read-only
}
Asymmetric Visibility (PHP 8.4) class Foo
{
Method keywords class Foo use FooTrait;
Keyword Description { }
public private(set) string $bar = 'baz';
Can be called statically, cannot
static }
access $this Attributes
Must be implemented by $foo = new Foo();
abstract #[Attribute(flags: Attribute::TARGET_CLASS)]
subclasses echo $foo->bar; // baz
$foo->bar = 'Foobar'; // Error class MyClassAttribute
final Subclasses cannot override {}

© Nic Wortel, Software Consultant & Trainer - Updated for PHP 8.4 - Last updated on November 6, 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.4 - Last updated on November 6, 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 count($array) Count elements in $array file_exists($filename) Return true if $filename exists

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

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

You might also like