Log in Sign up

Conditions

if ($age >= 18) {
    echo "adult";
} elseif ($age >= 13) {
    echo "teen";
} else {
    echo "child";
}

switch ($role) {            // loose comparison (==)
    case 'admin':
        $level = 3;
        break;
    default:
        $level = 1;
}

$level = match ($role) {    // PHP 8: strict (===), returns a value, no break needed
    'admin'          => 3,
    'editor', 'mod'  => 2,
    default          => 1,
};

Loops

for ($i = 0; $i < 10; $i++) { ... }

while ($row = $stmt->fetch()) { ... }

do { ... } while ($condition);

foreach ($items as $item) { ... }
foreach ($items as $key => $value) { ... }
foreach ($items as &$value) { $value *= 2; } unset($value); // by reference

break leaves a loop, continue jumps to the next pass (break 2 leaves two nested loops).

Including files

CommandIf file is missingLoads twice?
include 'a.php';warning, script continuesyes
require 'a.php';fatal error, script stopsyes
include_once / require_onceas aboveno

Use require_once __DIR__ . '/config.php'; – __DIR__ makes the path independent of the working directory.

Functions

function greet(string $name, string $greeting = "Hello"): string
{
    return "$greeting, $name!";
}

echo greet("Anna");                       // Hello, Anna!
echo greet(greeting: "Hi", name: "Ben");  // named arguments (PHP 8)

function sum(int ...$numbers): int {      // variadic
    return array_sum($numbers);
}
sum(1, 2, 3);
sum(...[1, 2, 3]);                        // spread

function find(int $id): ?array { ... }    // ?array = array or null
function writeLog(string|array $msg): void { ... } // union type, no return value

Function names must not clash with built-in functions (e.g. log, count) – that is a fatal error.

Closures and arrow functions

$tax = 0.19;

$withTax = function (float $p) use ($tax): float {  // use() imports variables
    return $p * (1 + $tax);
};

$withTax = fn(float $p): float => $p * (1 + $tax);  // arrow fn: imports automatically

$prices = array_map($withTax, [10, 20]);

Useful function helpers

FunctionPurpose
function_exists('name')check before declaring/calling
call_user_func($fn, ...$args)call a callable
is_callable($x)check if callable
func_get_args()all passed arguments
static $count = 0;variable that keeps its value between calls

Previous: PHP Basics: Syntax, Variables and Output · Next: PHP String Functions

Put together with AI as a quick reference I keep for my own work. Entries like this are usually not reviewed in detail by a person.