Cheatsheet for some Php knowledge you will frequently encounter in modern projects.

Overview

Modern Php Cheatsheet

Modern Php Cheatsheet

If you like this content, you can ping me or follow me on Twitter 👍

Tweet for help

Introduction

Motivation

This document is a cheatsheet for Php you will frequently encounter in modern projects and most contemporary sample code.

This guide is not intended to teach you Php from the ground up, but to help developers with basic knowledge who may struggle to get familiar with modern codebases (or let's say to learn Laravel or Symfony for instance) because of the new Php concepts and features introduced over the years.

Note: Concepts introduced here are based on the most recent version of php available (Php8.0 at the time of the last update)

Complementary Resources

When you struggle to understand a notion, I suggest you look for answers on the following resources:

Table of Contents

Notions

Function default parameter value

You can set default value to your function parameters:

function myFunction($param = 'foo') {
    return $param;
}
$a = myFunction();
// $a = 'foo'

$b = myFunction('bar');
// $b = 'bar'

But if you send null or an undefined property, default value won't be used:

function myFunction($param = 'foo') {
    return $param;
}
$a = myFunction(null);
// $a = null

$b = myFunction($undefined); // PHP Warning:  Undefined variable $undefined
// $b = null

Type hint

With Type hinting you can specify the expected data type for a property. It supports many types like scalar types (int, string, bool, and float) but also array, iterable, object, stdClass, etc.

You can set a type to a function's parameter:

function myFunction(int $param) {
    return $param;
}
$a = myFunction(10);
// $a = 10
$b = myFunction('foo'); // TypeError: myFunction(): Argument #1 ($param) must be of type int, string given

You can set a return type to a function:

function myFunction() : int {
    return 'foo';
}
$a = myFunction(); // TypeError: myFunction(): Return value must be of type int, string returned

When a function should not return something, you can use the type "void":

function myFunction() : void {
    return 'foo';
}
// PHP Fatal error:  A void function must not return a value

You cannot return null either:

function myFunction() : void {
    return null;
}
// PHP Fatal error:  A void function must not return a value

However, using return to exit the function is valid:

function myFunction() : void {
    return;
}
$a = myFunction();
// $a = null

You can set a return type to a class property:

Class Foo() {
    public int $bar;
}
$f = new Foo();
$f->bar = 'baz'; // TypeError: Cannot assign string to property Foo::$bar of type int

Union type hint

You can use a “union type” that accepts values of multiple different types, rather than a single one:

function myFunction(string|int|array $param) : string|int|array {
    return $param;
}

It also works with class property:

Class Foo() {
    public string|int|array $bar;
}

Nullable type hint

When a parameter has no type, it can accept null value:

function myFunction($param) {
    return $param;
}
$a = myFunction(null);
// $a = null

But as soon as a parameter has a type hint, it won't accept null value anymore and you'll get an error:

function myFunction(string $param) {
    return $param;
}
$a = myFunction(null); // TypeError: myFunction(): Argument #1 ($param) must be of type string, null given

If a function has a return type hint, it won't accept null value either:

function myFunction() : string {
    return null;
}
$a = myFunction(); // TypeError: myFunction(): Return value must be of type string, null returned

You can make a type hint explicitly nullable:

function myFunction(?string $param) {
    return $param;
}
$a = myFunction(null);
// $a = null

or with a union type:

function myFunction(string|null $param) {
    return $param;
}
$a = myFunction(null);
// $a = null

It also works with return type:

function myFunction(?string $param) : ?string {
    return $param;
}
// or
function myFunction(string|null $param) : string|null {
    return $param;
}

But void cannot be nullable:

function myFunction() : ?void {} // PHP Fatal error:  Void type cannot be nullable
// or
function myFunction() : void|null {} // PHP Fatal error:  Void type cannot be nullable

You can set a nullable type to a class property:

Class Foo() {
    public int|null $bar;
}
$f = new Foo();
$f->bar = null;
$a = $f->bar;
// $a = null

Destructuring arrays

You can destructure arrays to pull out several elements into separate variables.

Indexed array

Considering an indexed array like :

$array = ['foo', 'bar', 'baz'];

You can destruct it using the list syntax:

list($a, $b, $c) = $array;

// $a = 'foo'
// $b = 'bar'
// $c = 'baz'

Or the shorthand syntax:

[$a, $b, $c] = $array;

// $a = 'foo'
// $b = 'bar'
// $c = 'baz'

You can skip elements:

list(, , $c) = $array;

// $c = 'baz'

Or the shorthand syntax:

[, , $c] = $array;

// $c = 'baz'

When you try to destruct an index that doesn't exist in the given array, you'll get a warning:

list($a, $b, $c, $d) = $array; // PHP Warning:  Undefined array key 3

// $a = 'foo'
// $b = 'bar'
// $c = 'baz'
// $d = null;

Associative array

Considering an associative array (string-keyed) like :

$array = [
    'foo' => 'value1',
    'bar' => 'value2',
    'baz' => 'value3',
];

Previous list syntax won't work with an associative array, and you'll get a warning:

list($a, $b, $c) = $array; // PHP Warning:  Undefined array key 0 ...

// $a = null
// $b = null
// $c = null

But since php 7.1.0 (~ dec 2016), you can destruct it with another syntax based on keys:

list('foo' => $a, 'bar' => $b, 'baz' => $c) = $array;

// $a = 'value1'
// $b = 'value2'
// $c = 'value3'

Or the shorthand syntax:

['foo' => $a, 'bar' => $b, 'baz' => $c] = $array;

// $a = 'value1'
// $b = 'value2'
// $c = 'value3'

You can also destruct only a portion of the array (The order doesn't matter):

['baz' => $c, 'foo' => $a] = $array;

// $a = 'value1'
// $c = 'value3'

When you try to destruct a key that doesn't exist in the given array, you'll get a warning:

list('moe' => $d) = $array; // PHP Warning:  Undefined array key "moe"

// $d = null

Null Coalescing

Since php 7.0 (~ dec 2015), you can use the null coalescing operator to provide a fallback when a property is null with no error nor warning:

$a = null;
$b = $a ?? 'fallback';

// $b = 'fallback'

It also works when property is undefined:

$a = $undefined ?? 'fallback';

// $a = 'fallback'

Every other value of the property won't trigger the fallback:

'' ?? 'fallback'; // ''
0 ?? 'fallback'; // 0
false ?? 'fallback'; // false

Null coalescing on array

If array key exists, then fallback isn't triggered:

$a = ['foo' => 'bar'];
$b = $a['foo'] ?? 'fallback';

// $b = 'bar'

But when array doesn't exist, fallback is triggered with no error nor warning:

$a = null;
$b = $a['foo'] ?? 'fallback';

// $b = 'fallback'

Or array property is undefined, fallback is triggered with no error nor warning:

$b = $undefined['foo'] ?? 'fallback';

// $b = 'fallback'

When array exist but key can't be found in the given array, fallback is triggered with no error nor warning:

$a = [];
$b = $a['foo'] ?? 'fallback';

// $b = 'fallback'

It also works with indexed arrays:

$a = ['foo'];

// reminder: $a[0] = 'foo'

$b = $a[1] ?? 'fallback';

// $b = 'fallback'

It also works with nested arrays. If nested array key exists, then fallback isn't triggered:

$a = [
   'foo' => [
      'bar' => 'baz'
   ]
];
$b = $a['foo']['bar'] ?? 'fallback';

// $b = 'baz'

But when nested key can't be found in the given array, fallback is triggered with no error nor warning:

$a = [
   'foo' => [
      'bar' => 'baz'
   ]
];
$b = $a['foo']['qux'] ?? 'fallback';

// $b = 'fallback'

Null coalescing on object

You can also use null coalescing operator with object.

Object's attribute

If object's attribute exists, then fallback isn't triggered:

$a = (object)[
    'foo' => 'bar'
];
$b = $a->foo ?? 'fallback';

// $b = 'bar'

But when object's attribute can't be found, fallback is triggered with no error nor warning:

$a = (object)[
    'foo' => 'bar'
];
$b = $a->baz ?? 'fallback';

// $b = 'fallback'
Object's method

You can also use the null coalescing operator on call to an object's method. If the given method exists, then fallback isn't triggered:

class Foo
{
    public function bar() {
        return 'baz';
    }
}

$a = new Foo();
$b = $a->bar() ?? 'fallback';

// $b = 'baz'

But when object's method returns null, fallback is triggered with no error nor warning:

class Foo
{
    public function bar() {
        return null;
    }
}

$a = new Foo();
$b = $a->bar() ?? 'fallback';

// $b = 'fallback'

If object's method can't be found, null coalescing won't work and you'll get an error:

class Foo
{
    public function bar() {
        return 'baz';
    }
}

$a = new Foo();
$b = $a->baz() ?? 'fallback'; // PHP Error:  Call to undefined method baz()
Chained method

When using chained methods on object and an intermediary element can't be found, null coalescing won't work and you'll get an error:

class Foo
{
    public function bar() {
        return (object)[];
    }
}

$a = new Foo();
$b = $a->bar()->baz() ?? 'fallback'; // PHP Error:  Call to undefined method baz()

Nullsafe operator

When trying to read a property or calling a method on null, you'll get a warning and an error:

foo(); // PHP Error: Call to a member function foo() on null ">
$a = null;
$b = $a->foo; // PHP Warning:  Attempt to read property "foo" on null
// $b = null

$c = $a->foo(); // PHP Error:  Call to a member function foo() on null

With the nullsafe operator, you can do both without warning nor error:

$a = null;
$b = $a?->foo;
// $b = null
$c = $a?->foo();
// $c = null

You can chain multiple nullsafe operators:

$a = null;
$b = $a?->foo?->bar;
// $b = null
$c = $a?->foo()?->bar();
// $c = null

An expression is short-circuited from the first null-safe operator that encounters null:

$a = null;
$b = $a?->foo->bar->baz();
// $b = null

Nullsafe operator has no effect if the target is not null:

baz(); // PHP Error: Call to a member function baz() on string ">
$a = 'foo';
$b = $a?->bar; // PHP Warning:  Attempt to read property "bar" on string
// $b = null
$c = $a?->baz(); // PHP Error:  Call to a member function baz() on string

Nullsafe operator can't handle arrays properly but still can have some effect:

bar; // PHP Warning: Undefined array key "foo" // $c = null $d = $a['foo']->bar(); // PHP Warning: Undefined array key "foo" // PHP Error: Call to a member function bar() on null $e = $a['foo']?->bar(); // PHP Warning: Undefined array key "foo" // $c = null ">
$a = [];
$b = $a['foo']->bar;
// PHP Warning:  Undefined array key "foo"
// PHP Warning:  Attempt to read property "bar" on null
// $b = null

$c = $a['foo']?->bar; // PHP Warning:  Undefined array key "foo"
// $c = null

$d = $a['foo']->bar();
// PHP Warning:  Undefined array key "foo"
// PHP Error:  Call to a member function bar() on null

$e = $a['foo']?->bar(); // PHP Warning:  Undefined array key "foo"
// $c = null

You cannot use the nullsafe operator to write, it is read only:

$a = null;
$a?->foo = 'bar'; // PHP Fatal error:  Can't use nullsafe operator in write context

Spread operator

Variadic parameter

Since php 5.6 (~ aug 2014), you can add a variadic parameter to any function that let you use an argument lists with variable-length:

function countParameters(string $param, string ...$options) : int {

    foreach ($options as $option) {
        // you can iterate on $options
    }
 
    return 1 + count($options);
}

countParameters('foo'); // 1
countParameters('foo', 'bar'); // 2
countParameters('foo', 'bar', 'baz'); // 3

Variadic parameter should always be the last parameter declared:

function countParameters(string ...$options, string $param) { ... }
// PHP Fatal error: Only the last parameter can be variadic

You can have only one variadic parameter:

function countParameters(string ...$options, string ...$moreOptions) { ... }
// PHP Fatal error: Only the last parameter can be variadic

It can't have a default value:

function countParameters(string $param, string ...$options = []) { ... }
// PHP Parse error: Variadic parameter cannot have a default value

When not typed, it accepts any value:

function countParameters(string $param, ...$options) : int {
    return 1 + count($options);
}

countParameters('foo', null, [], true); // 4

When typed, you have to use properly typed values:

function countParameters(string $param, string ...$options) : int {
    return 1 + count($options);
}

countParameters('foo', null);
// TypeError: countParameters(): Argument #2 must be of type string, null given

countParameters('foo', []);
// TypeError: countParameters(): Argument #2 must be of type string, array given

Argument unpacking

Arrays and traversable objects can be unpacked into argument lists when calling functions by using the spread operator:

function add(int $a, int $b, int $c) : int {
    return $a + $b + $c;
}
$array = [2, 3];
$r = add(1, ...$array);

// $r = 6

The given array can have more elements than needed:

function add(int $a, int $b, int $c) : int {
    return $a + $b + $c;
}
$array = [2, 3, 4, 5];
$r = add(1, ...$array);

// $r = 6

The given array can't have lesser elements than needed:

function add(int $a, int $b, int $c) : int {
    return $a + $b + $c;
}
$array = [2];
$r = add(1, ...$array); // TypeError: Too few arguments to function add(), 2 passed

Except when some function arguments have a default value:

function add(int $a, int $b, int $c = 0) : int {
    return $a + $b + $c;
}
$array = [2];
$r = add(1, ...$array);
// $r = 3

If an argument is typed and the passed value does not match the given type, you'll get an error:

function add(int $a, int $b, int $c) : int {
    return $a + $b + $c;
}
$array = ['foo', 'bar'];
$r = add(1, ...$array); // TypeError: add(): Argument #2 ($b) must be of type int, string given

It is possible to use an associative array, but keys should match arguments names

2, "c" => 3 ]; $r = add(1, ...$array); // $r = 6 ">
function add(int $a, int $b, int $c) : int {
    return $a + $b + $c;
}
$array = [
    "b" => 2,
    "c" => 3
];
$r = add(1, ...$array);
// $r = 6

Order of the elements in the associative array doesn't matter:

3, "b" => 2, ]; $r = add(1, ...$array); // $r = 6 ">
function add(int $a, int $b, int $c) : int {
    return $a + $b + $c;
}
$array = [
    "c" => 3,
    "b" => 2,
];
$r = add(1, ...$array);
// $r = 6

If a key doesn't match an argument's name, you'll get an error:

2, "c" => 3, "d" => 4, ]; $r = add(1, ...$array); // PHP Error: Unknown named parameter $d ">
function add(int $a, int $b, int $c) : int {
    return $a + $b + $c;
}
$array = [
    "b" => 2,
    "c" => 3,
    "d" => 4,
];
$r = add(1, ...$array); // PHP Error:  Unknown named parameter $d

Array unpacking

Indexed array

When you want to merge multiple arrays, you generally use array_merge:

$array1 = ['baz'];
$array2 = ['foo', 'bar'];

$array3 = array_merge($array1,$array2);
// $array3 = ['baz', 'foo', 'bar']

But since php 7.4 (~ nov 2019), you can unpack indexed arrays, with spread operator:

$array1 = ['foo', 'bar'];
$array2 = ['baz', ...$array1];
// $array2 = ['baz', 'foo', 'bar']

Elements will be merged in the order they are passed:

$array1 = ['foo', 'bar'];
$array2 = ['baz', ...$array1, "qux"];
// $array2 = ['baz', 'foo', 'bar', "qux"]

It doesn't do any deduplication:

$array1 = ['foo', 'bar'];
$array2 = ['foo', ...$array1];
// $array2 = ['foo', 'foo', 'bar']

You can unpack multiple arrays at once:

$array1 = ['foo', 'bar'];
$array2 = ['baz'];
$array3 = [ ...$array1, ...$array2];
// $array3 = ['foo', 'bar', 'baz']

You can unpack the same array multiple times:

$array1 = ['foo', 'bar'];
$array2 = [ ...$array1, ...$array1];
// $array2 = ['foo', 'bar', 'foo', 'bar']

You can unpack an empty array with no error nor warning:

$array1 = [];
$array2 = ['foo', ...$array1];
// $array2 = ['foo']

You can unpack an array that has not been previously stored in a property:

$array1 = [...['foo', 'bar'], 'baz'];
// $array1 = ['foo', 'bar', 'baz']

If you try to unpack an array valued with null, you'll get an error:

$array1 = null;
$array2 = ['foo', ...$array1]; // PHP Error:  Only arrays and Traversables can be unpacked

You can unpack the result of a function/method:

function getArray() : array {
  return ['foo', 'bar'];
}

$array = [...getArray(), 'baz']; 
// $array = ['foo', 'bar', 'baz']
You might also like...
PHP exercises from my course at ETEC and some of my own play-around with PHP

etec-php-exercises PHP exercises from my course at ETEC and some of my own play-around with PHP Translations: Português (BR) Projects Project Descript

This composer plugin allows you to share your selected packages between your projects by creating symlinks
This composer plugin allows you to share your selected packages between your projects by creating symlinks

Composer - Shared Package Plugin This composer plugin allows you to share your selected packages between your projects by creating symlinks. All share

 A complete solution for group projects in organizations that lets you track your work in any scenario. Working in a team is a cumbersome task, ease it using our project management system.
A complete solution for group projects in organizations that lets you track your work in any scenario. Working in a team is a cumbersome task, ease it using our project management system.

SE-Project-Group24 What is Evolo? Evolo is Dashboard based Project Management System. A complete solution for group projects in organizations that let

A simple GitScrum plugin for Wordpress. You will be able to manage your projects without having to leave Wordpress.
A simple GitScrum plugin for Wordpress. You will be able to manage your projects without having to leave Wordpress.

GitScrum Plugin for Wordpress A simple GitScrum plugin for Wordpress. You will be able to manage your projects without having to leave Wordpress. GitS

the repository uses some of the code from php-meminfo to simplify integration

the repository uses some of the code from php-meminfo to simplify integration

Some exercises to practice whiteboard interview questions in PHP.
Some exercises to practice whiteboard interview questions in PHP.

PHP Interview Exercises · A number of exercises to practice whiteboard interview questions in PHP. Inside exercises directory, you can find folders co

Small library providing some functional programming tools for PHP, based on Rambda

Functional library for PHP. Features: set of useful functions helpful in functional programming all functions are automatically curried every array ca

This project backports features found in the latest PHP versions and provides compatibility layers for some extensions and functions

This project backports features found in the latest PHP versions and provides compatibility layers for some extensions and functions. It is intended to be used when portability across PHP versions and extensions is desired.

Examples of some common design patterns implemented in php

What is a Design Pattern? Design patterns are typical solutions to common problems in software design. Each pattern is like a blueprint that you can c

Comments
  • Add swapping variables example

    Add swapping variables example

    Hi there, thanks for this awesome cheatsheet. I think it's also worth mentioning swapping variables using destructuring assignments. What do you think about this?

    opened by yusuftaufiq 1
  • Add a section on named arguments

    Add a section on named arguments

    • https://php.watch/versions/8.0/named-parameters
    • https://www.php.net/releases/8.0/en.php#named-arguments
    • https://stitcher.io/blog/php-8-named-arguments
    enhancement 
    opened by smknstd 1
  • Add Translations to Other Languages

    Add Translations to Other Languages

    As the information in this cheat sheet is extremely useful to a large PHP audience, it would be neat to have it translated into other (human) languages. I'm willing to contribute, will start with Russian.

    opened by Menelion 5
Owner
Arnaud Becher
Let me be what I wanna be
Arnaud Becher
YCOM Impersonate. Login as selected YCOM user 🧙‍♂️in frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Friends Of REDAXO 17 Sep 12, 2022
🎓 Collection of useful PHP frequently asked questions, articles and best practices

PHP.earth documentation These files are available online at PHP.earth. Contributing and license We are always looking forward to see your contribution

PHP.earth 278 Dec 27, 2022
Regexp Security Cheatsheet

Regexp Security Cheatsheet Research was done to find "weak places" in regular expressions of Web Application Firewalls (WAFs). Repository contains SAS

Vlad I 610 Dec 25, 2022
Simple, modern looking server status page with administration and some nice features, that can run even on shared webhosting

Simple, modern looking server status page with administration and some nice features, that can run even on shared webhosting

Server status project 363 Dec 28, 2022
A repository for showcasing my knowledge of the PHP programming language, and continuing to learn the language.

Learning PHP (programming language) I know very little about PHP. This document will list all my knowledge of the PHP programming language. Basic synt

Sean P. Myrick V19.1.7.2 2 Oct 29, 2022
The Easiest way to start using PHP CS Fixer and PHP_CodeSniffer with 0-knowledge

The Easiest Way to Use Any Coding Standard Features Blazing fast Parallel run Use PHP_CodeSniffer || PHP-CS-Fixer - anything you like 2nd run under fe

null 1.1k Jan 6, 2023
🐋 This project aims to broaden knowledge of system administration by using Docker: virtualizing several Docker images, creating them in a new personal virtual machine.

?? This project aims to broaden knowledge of system administration by using Docker: virtualizing several Docker images, creating them in a new personal virtual machine.

Anton Kliek 1 Jan 26, 2022
PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects.

?? Yell PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects. Requirement

Zeeshan Ahmad 20 Dec 8, 2018
The fixture plugin is really helpful if you want to create some static demo data for your shopware instance.

Fixture Plugin The fixture plugin is really helpful if you want to create some static demo data for your shopware instance. Installation Just add it t

basecom 7 Nov 7, 2022