PHP cheatsheet

PHP Full Cheatsheet

A complete PHP cheatsheet with modern syntax, practical recipes, operators, arrays, OOP, security essentials, and more.

Core syntax

  • Use PHP tags only when you are rendering PHP code.
  • Declare strict types for clearer contracts and fewer surprises.
  • Prefer echo for output and var_dump/print_r for debugging.
<?php

declare(strict_types=1);

$name = 'Ada';
echo "Hello $name";

Variables and types

  • Strings, integers, floats, booleans, arrays, objects, and null are all first-class PHP types.
  • Use isset() to check whether a variable exists and is not null.
  • Use null coalescing to provide safe fallback values.
$name = 'Ada';
$isActive = true;
$amount = 19.95;
$displayName = $name ?? 'Guest';

Conditionals and loops

  • Use match expressions when you want a readable branching alternative to switch.
  • Break and continue remain useful inside loops.
  • Strict comparison is safer than loose comparison for logic checks.
if ($status === 'published') {
    echo 'Live';
} elseif ($status === 'draft') {
    echo 'Draft';
} else {
    echo 'Unknown';
}

foreach (['a', 'b', 'c'] as $value) {
    echo $value;
}

Arrays and functions

  • Arrays can be indexed, associative, or multidimensional.
  • array_filter(), array_map(), and array_reduce() are strong helpers for transformations.
  • Functions are easier to reuse when you add clear parameter and return types.
$users = ['Ada', 'Grace'];
$users[] = 'Linus';

function greet(string $name): string {
    return "Hello $name";
}

Object-oriented PHP

  • Classes, interfaces, and traits are useful when you need reusable structure.
  • Constructor promotion keeps class declarations concise.
  • Enums are a good fit when a value must come from a fixed set.
class User {
    public function __construct(protected string $name) {}
}

interface Notifier {
    public function send(string $message): void;
}

Security and database access

  • Escape output with htmlspecialchars() before rendering user content in HTML.
  • Prefer password_hash() and password_verify() for credentials.
  • Use PDO with prepared statements for safer database access.
$hash = password_hash($password, PASSWORD_DEFAULT);
$valid = password_verify($password, $hash);

Get In Touch


Ready to discuss your next project? Drop me a message.