PHP cheatsheet

Naming convention

1
2
3
4
5
6
<?php
$first_name = 'Angeles'. // all lower case with underscore separators
function updateProduct(){} // camelCase
class ProductItem{} // StudlyCaps
const ACCESS_KEY = '123abc'; // all upper case with underscore separators
?>

Output

1
echo 'Hello World';

Variable declaration

1
2
3
4
$name = 'Angeles'; //string
$is_active = true; //boolean
$number = 7; //integer
$amount = 99.99; //float

Strings

  • Concatenate

    1
    echo 'Hello ' . $name;
  • Escape characters

    1
    2
    //string escape characters \n new line  \t tab  \\ backslash
    echo "Hello Angeles\nHello Juan";
  • Interpolation

    1
    echo "Hello $name";
  • Length

    1
    echo strlen($name);
  • Remove spaces

    1
    2
    // Remove space(s) before and after
    echo trim($text)
  • Convert cases

    1
    2
    3
    4
    echo strtolower($email);
    echo strtoupper($name);
    // Converts the first character to uppercase
    echo ucfirst($name); // 'Angeles'
  • Replace

    1
    2
    // Replace text a by text b in $text
    echo str_replace('a', 'b', $text);
  • Contains (PHP 8)

    1
    echo str_contains($name, 'ke')  # true

Numeric

  • Check

    1
    echo is_numeric('59.99'); # true
  • round number

    1
    2
    3
    // Round a number
    echo(round(0.80)); // returns 1
    echo(round(0.49)); // returns 0
  • Random

    1
    echo(rand(10, 100)); # 89

Nullable

  • Null coalesce operator

    1
    echo $name ?? 'Angeles';  //output 'Angeles' if $name is null
  • Null coalesce assignment

    1
    $name ??= 'Angeles';
  • Null safe operator (PHP 8)

    1
    2
    // return null if one ? is null
    echo $user?->profile?->activate();
  • Null safe + Null coalesce

    1
    2
    // if null, return 'Not applicable'
    echo $user?->profile?->activate() ?? 'Not applicable';

Spaceship

  • Combined comparison which will retun:
    • 0 if values on either side are equal
    • 1 if the value on the left is greater
    • -1 if the value on the right is greater
1
2
3
4
5
6
//Spaceship operator return -1 0 1
$names = ['Angeles', 'Juan', 'Luis']
usort($names, function($a, $b) {
return $a <=> $b;
}
// ['Angeles', 'Juan', 'Luis']

Debug

  • Print variables contents

    1
    2
    var_dump($names);
    print_r($names);
  • Terminate the current script

    1
    die();

Conditionals

  • Ternary operator

    1
    2
    // Ternary operator (true : false)
    echo $valid ? 'user valid' : 'user not valid';
  • If-else

    1
    2
    3
    4
    5
    6
    7
    8
    //Conditionals
    if ($condition == 10) {
    echo 'condition 10'
    } elseif ($condition == 5) {
    echo 'condition 5'
    } else {
    echo 'all other conditions'
    }
  • Compare

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // equal no type check
    $var_1 == var_2
    // equal with type check
    $var_1 === var_2
    //not equal
    $var_1 != var_2
    //or
    $var_1 || var_2
    //and
    $var_1 && var_2
    //greater than
    $var_1 > var_2
    //less than
    $var_1 < var_2
  • Match expression (PHP 8)

    1
    2
    3
    4
    5
    6
    $type = match($color) {
    'red' => 'danger',
    'yellow', 'orange' => 'warning',
    'green' => 'success',
    default => 'Unknown'
    };

Loops

  • For

    1
    2
    3
    4
    //for loop
    for ($i = 0; $i < 20; $i++) {
    echo "i value = " . i;
    }
  • While

    1
    2
    3
    4
    5
    $number = 1;
    while ($number < 10) {
    echo 'value : ' . $number ;
    $number += 1;
    }
  • Do while

    1
    2
    3
    4
    5
    $number = 1;
    do {
    echo 'value : ' . $number ;
    $number += 1;
    } while ($number < 10);

Arrays

  • Array declaration

    1
    $names = ['Angeles', 'Juan'];
  • Add to array

    1
    2
    3
    $names = ['Angeles', 'Juan'];
    $names[] = 'Luis';
    // names: ['Angeles', 'Juan', 'Luis',
  • Spread operator

    1
    2
    3
    $names = ['Angeles', 'Juan', 'Luis'];
    $people = ['Manuel', ...$names];
    // people: ['Manuel', 'Angeles', 'Juan', 'Luis']
  • Remove array entry

    1
    2
    3
    $names = ['Angeles', 'Juan'];
    unset($names['Angeles']);
    // output: ['Angeles', 'Juan']
  • Array to string

    1
    2
    3
    $names = ['Angeles', 'Juan'];
    echo implode(', ', $names)
    //output: 'Angeles, Juan'
  • String to Array

    1
    2
    3
    $text = 'Angeles, Juan'
    echo explode(',', $text);
    // output: ['Angeles', 'Juan']
  • Direct access

    1
    2
    3
    $names = ['Angeles', 'Juan'];
    echo $names[1]
    //output: Angeles
  • Loop for each array entry

    1
    2
    3
    foreach($names as $name) { 
    echo 'Hello ' . $name;
    }
  • Loop break / continue

    1
    2
    3
    4
    5
    6
    7
    8
    $values = ['one', 'two', 'three'];
    foreach ($values as $value) {
    if ($value === 'two') {
    break; // exit loop
    } elseif ($value === 'three') {
    continue; // next loop iteration
    }
    }
  • Number of items in a Array

    1
    echo count($names);  
  • Associative array:

    1
    $person = ['age' => 30, 'hair' => 'dark'];
  • Add to associative array

    1
    $person['name'] = 'Angeles';
  • Loop associative array (key => value)

    1
    2
    3
    foreach($names as $key => $value) { 
    echo $key . ' : ' . $value
    }
  • Check if a specific key exist

    1
    echo array_key_exist('age', $person);
  • Return keys

    1
    2
    echo array_keys($person);
    // ['age', 'hair']
  • Return values

    1
    2
    echo array_values($person)
    // [30, 'dark']
  • Array filter (return a filtered array)

    1
    2
    3
    $filtered_people = array_filter($people, function ($person) {
    return $names->active;
    })
  • Array map (return transform array):

    1
    2
    3
    $only_names = array_map(function($person) {
    return [‘name’ => $person->name];
    }, $people)

Functions

  • Function declararion

    1
    2
    3
    function name($first_name, $last_name = 'default value') {
    puts $first_name . ' ' . $last_name
    }
  • Function call

    1
    name('Angeles', 'Broullon');
  • Function call with named parameters (PHP 8)

    1
    2
    name(first_name: 'Angeles', last_name: 'Broullon');
    // order can change
  • Function variables params

    1
    2
    3
    function name(...$params) {
    return $params[0] . “ “ . params[1];
    }
  • Closure function

    1
    2
    3
    Route::get('/', function () {
    return view('welcome');
    });
  • Arrow functions

    1
    Route::get('/', fn () => return view('welcome');

Files

  • File read

    1
    $file = fopen("test.txt", "r");
  • Output lines until EOF is reached

    1
    2
    3
    4
    5
    while(! feof($file)) {
    $line = fgets($file);
    echo $line. "<br>";
    }
    fclose($file);
  • File write

    1
    2
    $file = fopen('export.csv', 'a');
    $array = ['name' => 'Angeles', 'age' => 30];
  • Write key name as csv header

    1
    fputcsv($file, array_keys($array[0]));
  • Write lines (format as csv)

    1
    2
    3
    4
    foreach ($array as $row) {
    fputcsv($file, $row);
    }
    fclose($file);

Error handling

  • Throw error

    1
    2
    3
    if (someCondition) {
    throw new Exception('Data format error');
    }
  • Catch the error

    1
    2
    3
    4
    5
    try {
    $db->checkData($data)
    } catch (Exception as $e)
    echo $e->getMessage();
    }

Classes

  • Class declaration

    1
    2
    class Person {
    }
  • Object instantiation

    1
    $person = new Person
  • Class properties and constructor

    1
    2
    3
    4
    5
    6
    7
    class Person {
    protected $first_name;
    protected $last_name;
    public function __construct($first_name, $last_name) {
    $this->first_name = $first_name;
    $this->last_name = $last_name
    }
  • Constructor Property Promotion (PHP 8)

    1
    2
    3
    4
    5
    6
    7
    class Person 
    {
    public function __construct(protected $first_name, protected $last_name)
    {

    }
    }
  • Static constructor

    1
    2
    3
    4
    public static function create(...$params) {
    return new self($params)
    }
    $person = Person::create(Angeles, ‘Broullon’);
  • Class inheritance

    1
    2
    3
    4
    5
    6
    class Customer extends Person {
    public function name() {
    parent::name();
    echo 'Override method';
    }
    }
  • Static method

    1
    2
    3
    4
    5
    class Greeting {
    public static function welcome() {
    echo "Hello World!";
    }
    }
  • Call static method

    1
    greeting::welcome();
  • Static method internal call

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Greeting {
    public static function welcome() {
    echo "Hello World!";
    }

    public function __construct() {
    self::welcome();
    }
    }

    new Greeting();

Interfaces

1
2
3
4
5
6
7
8
9
10
11
interface Animal {
public function makeSound();
}

class Cat implements Animal {
public function makeSound() {
echo "Meow";
}
}
$animal = new Cat();
$animal->makeSound();

Trait (mix-in)

1
2
3
4
5
6
7
8
9
10
11
12
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}

class Greetings {
use HelloWorld;
}

$object = new Greetings();
$object->sayHello();