LATEST >>

Welcome Here And Thanks For Visiting. Like Us On Facebook...

EXEIdeas – Let's Your Mind Rock » HTML-CSS-PHP-JavaScript » Ultimate PHP Cheat Sheet Every Developer Must Know In 2026

Ultimate PHP Cheat Sheet Every Developer Must Know In 2026

Ultimate-PHP-Cheat-Sheet-Every-Developer-Must-Know-In-2026

PHP has evolved far beyond the procedural scripting language many developers remember from older websites. Modern PHP includes strict typing, union and intersection types, enums, attributes, readonly classes, constructor property promotion, match expressions, null-safe access, property hooks, asymmetric visibility, modern password APIs, PDO, Composer, attributes, fibers, and PHP 8.5’s new pipe operator and URI functionality.

That creates a new challenge: even experienced PHP developers cannot realistically keep every function, syntax rule, array utility, date format, PDO pattern, session setting, JSON flag, and modern language feature memorized.

A good PHP cheat sheet therefore should not simply list functions alphabetically. It should organize the parts of PHP that developers actually use while building websites, APIs, SaaS applications, admin panels, automation tools, and backend services.

The Best PHP Cheat Sheet Is Not A List Of Everything PHP Can Do. It Is A Fast Reference To The Syntax, Functions, Security Practices, Language Features, And Production Patterns You Need Repeatedly While Building Real Applications.

This 2026 PHP cheat sheet covers the fundamentals, modern PHP 8.x syntax, arrays, strings, functions, OOP, enums, attributes, PHP 8.4 property features, PHP 8.5 capabilities, PDO, JSON, files, dates, sessions, authentication, HTTP requests, Composer, CLI commands, error handling, security, and production practices.

Table of Contents

PHP Version Basics For 2026

Modern production PHP should run on a currently supported PHP branch. In late 2026, PHP 8.2 through PHP 8.5 remain within PHP’s official support lifecycle, although PHP 8.2 is approaching the end of its security-support period.

For new projects, choose a modern supported version that is compatible with your dependencies rather than starting development on an aging runtime.

Check your installed PHP version:

php -v

Inside PHP:

<?php
echo PHP_VERSION;
echo PHP_MAJOR_VERSION;
echo PHP_MINOR_VERSION;
?>

Check loaded extensions:

php -m

Check the active configuration:

php --ini

Basic PHP Syntax

PHP code begins with the standard opening tag:

<?php

echo 'Hello, PHP!';

?>

For PHP-only files, the closing ?> tag is usually omitted to avoid accidental output after the PHP block.

Comments

// Single-line comment

# Another single-line comment

/*
    Multi-line comment
*/

Output

echo 'Hello';

print 'Hello';

printf('Price: %.2f', 19.99);

echo is commonly used for straightforward output, while printf() is useful when formatted output is required.

Variables And Constants

PHP variables begin with $.

$name = 'Muzammil';
$age = 34;
$isActive = true;
$price = 99.95;

Variable names are case-sensitive:

$name = 'Ali';
$Name = 'Ahmed';

These are different variables.

Constants

const APP_NAME = 'My Application';

define('API_VERSION', 'v1');

echo APP_NAME;
echo API_VERSION;

Prefer const where compile-time declaration is suitable.

PHP Scalar And Compound Types

Common PHP types include:

  • string
  • int
  • float
  • bool
  • array
  • object
  • callable
  • iterable
  • null
  • resource

Modern PHP also supports type combinations such as union types.

function normalizeId(int|string $id): string
{
    return (string) $id;
}

Enable Strict Types

For modern application code, strict typing can make type-related bugs easier to catch.

<?php

declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

The declaration applies to the file in which it appears.

Strict types are particularly useful in domain logic, services, API layers, and reusable packages.

Type Casting Cheat Sheet

$number = (int) '42';

$price = (float) '10.50';

$text = (string) 123;

$enabled = (bool) 1;

$list = (array) $value;

For validation, however, explicit validators are often safer than blindly casting untrusted data.

Null Coalescing Operator

Use ?? when a value may not exist or may be null.

$name = $_POST['name'] ?? 'Guest';

This is cleaner than repeatedly combining isset() with a ternary expression.

Null Coalescing Assignment

$config['timezone'] ??= 'UTC';

The assignment occurs only when the target is missing or null.

Null-Safe Operator

The null-safe operator prevents repeated null checks when traversing objects.

$country = $user?->address?->country;

If an intermediate object is null, the entire expression returns null instead of attempting the next property access.

Comparison Operators

$a == $b;    // Equal after type juggling

$a === $b;   // Same value and same type

$a != $b;    // Not equal

$a !== $b;   // Not identical

$a > $b;
$a < $b;
$a >= $b;
$a <= $b;

For most application logic, prefer strict comparison with === and !== unless type coercion is intentionally required.

Spaceship Operator

$result = $a <=> $b;

The result is:

  • -1 when the left value is smaller.
  • 0 when values are equal.
  • 1 when the left value is greater.

It is particularly useful inside sorting callbacks.

Conditionals

if ($age >= 18) {
    echo 'Adult';
} elseif ($age >= 13) {
    echo 'Teenager';
} else {
    echo 'Child';
}

Ternary Operator

$status = $active ? 'Active' : 'Inactive';

Match Expression

The match expression is stricter and often cleaner than switch.

$message = match ($status) {
    'paid'     => 'Payment Complete',
    'pending'  => 'Payment Pending',
    'failed'   => 'Payment Failed',
    default    => 'Unknown Status',
};

match uses strict comparison and returns a value.

Switch Statement

switch ($role) {
    case 'admin':
        echo 'Administrator';
        break;

    case 'member':
        echo 'Member';
        break;

    default:
        echo 'Unknown';
}

For simple value mapping, modern PHP code often benefits from match.

Loops

For Loop

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

While Loop

while ($condition) {
    // Work
}

Do While Loop

do {
    // Executes at least once
} while ($condition);

Foreach Loop

foreach ($users as $user) {
    echo $user['name'];
}

With key and value:

foreach ($users as $id => $user) {
    echo $id;
    echo $user['name'];
}

Break And Continue

foreach ($numbers as $number) {

    if ($number === 5) {
        continue;
    }

    if ($number > 100) {
        break;
    }
}

PHP Arrays

PHP arrays can behave as indexed lists or associative maps.

Indexed Array

$colors = ['red', 'green', 'blue'];

echo $colors[0];

Associative Array

$user = [
    'id' => 10,
    'name' => 'Ali',
    'email' => 'ali@example.com',
];

Nested Array

$users = [
    [
        'id' => 1,
        'name' => 'Ali',
    ],
    [
        'id' => 2,
        'name' => 'Ahmed',
    ],
];

Most Useful PHP Array Functions

count($items);

array_keys($items);

array_values($items);

array_key_exists('email', $user);

in_array('admin', $roles, true);

array_search('admin', $roles, true);

array_merge($first, $second);

array_unique($items);

array_reverse($items);

array_slice($items, 0, 10);

array_chunk($items, 100);

When checking values with in_array() or array_search(), the strict third parameter is often safer.

Array Map

$names = array_map(
    fn(array $user): string => $user['name'],
    $users
);

Array Filter

$activeUsers = array_filter(
    $users,
    fn(array $user): bool => $user['active']
);

Array Reduce

$total = array_reduce(
    $orders,
    fn(float $sum, array $order): float => $sum + $order['total'],
    0.0
);

Array Destructuring

[$firstName, $lastName] = ['Ali', 'Khan'];

Associative destructuring:

[
    'id' => $id,
    'email' => $email,
] = $user;

Array Spread Operator

$combined = [
    ...$first,
    ...$second,
];

This can make collection composition cleaner than repeated manual loops.

String Basics

Single-quoted strings perform less interpolation:

$name = 'Ali';

echo 'Hello $name';

Double-quoted strings interpolate variables:

echo "Hello {$name}";

Common String Functions

strlen($text);

trim($text);

ltrim($text);

rtrim($text);

strtolower($text);

strtoupper($text);

str_contains($text, 'PHP');

str_starts_with($text, 'PHP');

str_ends_with($text, '2026');

str_replace('old', 'new', $text);

substr($text, 0, 20);

explode(',', $text);

implode(', ', $items);

Multibyte String Functions

When working with Unicode text, use the mbstring extension where character-aware behavior is required.

mb_strlen($text);

mb_strtolower($text);

mb_strtoupper($text);

mb_substr($text, 0, 20);

PHP 8.4 also expanded the multibyte API with functions such as:

mb_trim($text);

mb_ltrim($text);

mb_rtrim($text);

mb_ucfirst($text);

mb_lcfirst($text);

Functions

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

Default Arguments

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

Named Arguments

$result = createUser(
    name: 'Ali',
    email: 'ali@example.com',
    active: true
);

Named arguments can improve readability when a function accepts several parameters, although publicly consumed parameter names then become part of the API contract.

Variadic Functions

function total(float ...$numbers): float
{
    return array_sum($numbers);
}

echo total(10, 20, 30);

Arrow Functions

$double = fn(int $number): int => $number * 2;

Arrow functions are useful for short callbacks because they automatically capture variables from the surrounding scope by value.

Anonymous Functions And Closures

$taxRate = 0.15;

$calculateTax = function (float $amount) use ($taxRate): float {
    return $amount * $taxRate;
};

First-Class Callables

$trimFunction = trim(...);

echo $trimFunction('  Hello  ');

This syntax creates a callable Closure from an existing callable.

Object-Oriented PHP Basics

class User
{
    public function __construct(
        public int $id,
        public string $name,
        private string $email
    ) {
    }

    public function getEmail(): string
    {
        return $this->email;
    }
}

This example uses constructor property promotion, which reduces repetitive property declarations and assignments.

Visibility Keywords

  • public: Accessible broadly.
  • protected: Accessible within the class and subclasses.
  • private: Accessible only within the declaring class.

Inheritance

class Admin extends User
{
    public function canManageUsers(): bool
    {
        return true;
    }
}

Interfaces

interface PaymentGateway
{
    public function charge(float $amount): bool;
}

An implementation:

class StripeGateway implements PaymentGateway
{
    public function charge(float $amount): bool
    {
        return true;
    }
}

Traits

trait HasTimestamps
{
    public function now(): DateTimeImmutable
    {
        return new DateTimeImmutable();
    }
}

Use in a class:

class Order
{
    use HasTimestamps;
}

Traits provide code reuse across otherwise unrelated classes, but they should not become a substitute for clear architecture.

Abstract Classes

abstract class Report
{
    abstract public function generate(): string;

    public function downloadName(): string
    {
        return 'report.txt';
    }
}

Static Members

class MathHelper
{
    public static function percent(float $value, float $rate): float
    {
        return $value * $rate;
    }
}

$result = MathHelper::percent(100, 0.15);

Readonly Properties

class Invoice
{
    public function __construct(
        public readonly int $id,
        public readonly float $total
    ) {
    }
}

Readonly properties can be initialized but cannot later be arbitrarily reassigned.

Readonly Classes

readonly class Coordinates
{
    public function __construct(
        public float $latitude,
        public float $longitude
    ) {
    }
}

Readonly classes are useful for immutable value objects.

Enums

Enums are one of the most useful modern PHP features for replacing fragile string constants.

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Cancelled = 'cancelled';
}

Usage:

$status = OrderStatus::Paid;

echo $status->value;

Convert from a value:

$status = OrderStatus::from('paid');

$status = OrderStatus::tryFrom($input);

tryFrom() returns null instead of throwing when no enum case matches.

Attributes

Attributes allow structured metadata to be attached to classes, methods, properties, parameters, and other declarations.

#[Attribute]
class Route
{
    public function __construct(
        public string $path
    ) {
    }
}

Usage:

#[Route('/users')]
class UserController
{
}

Frameworks and libraries can inspect attributes through reflection.

PHP 8.4 Property Hooks

PHP 8.4 introduced property hooks, allowing get and set behavior to be attached directly to properties.

class User
{
    public string $name {
        set => trim($value);
    }
}

Computed properties can also use getters:

class Rectangle
{
    public function __construct(
        public float $width,
        public float $height
    ) {
    }

    public float $area {
        get => $this->width * $this->height;
    }
}

Property hooks can reduce boilerplate getter and setter methods, but use them when they improve the domain model rather than simply because the feature exists.

PHP 8.4 Asymmetric Property Visibility

PHP 8.4 also allows different read and write visibility.

class Account
{
    public private(set) string $status = 'active';

    public function suspend(): void
    {
        $this->status = 'suspended';
    }
}

External code can read the property while direct external writes remain restricted.

PHP 8.5 Pipe Operator

PHP 8.5 introduced the pipe operator |>, allowing values to flow through callables from left to right.

$title = '  Ultimate PHP Cheat Sheet  ';

$slug = $title
    |> trim(...)
    |> strtolower(...)
    |> (fn(string $value): string => str_replace(' ', '-', $value));

This can make certain transformation pipelines easier to read than deeply nested function calls.

PHP 8.5 URI API

PHP 8.5 added a modern URI extension for standards-aware URI and URL handling.

Conceptually:

use Uri\Rfc3986\Uri;

$uri = new Uri('https://example.com/products?id=10');

echo $uri->getHost();

This provides a more structured approach to URI manipulation than relying only on older string-oriented URL processing.

PHP 8.5 NoDiscard Attribute

PHP 8.5 introduced #[\NoDiscard] so APIs can indicate that ignoring a return value is potentially a mistake.

#[\NoDiscard]
function saveOrder(): bool
{
    return true;
}

This is useful for APIs where success or failure must not be silently ignored.

Exceptions

try {
    processPayment();
} catch (PaymentException $e) {
    // Handle expected payment failure
} catch (Throwable $e) {
    // Handle unexpected failure
} finally {
    // Always runs
}

Throw an exception:

throw new RuntimeException('Unable to process request.');

Throwable

Both traditional exceptions and many PHP engine errors implement Throwable.

try {
    riskyOperation();
} catch (Throwable $e) {
    error_log($e->getMessage());
}

Avoid catching every Throwable only to silently ignore failures.

Useful Exception Information

$e->getMessage();

$e->getCode();

$e->getFile();

$e->getLine();

$e->getTrace();

$e->getPrevious();

Detailed exception data belongs in protected logs, not public production responses.

Ultimate-PHP-Cheat-Sheet-Every-Developer-Must-Know

PDO Database Connection

$pdo = new PDO(
    'mysql:host=localhost;dbname=app;charset=utf8mb4',
    $username,
    $password,
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
);

PDO Select Query

$stmt = $pdo->prepare(
    'SELECT id, name, email
     FROM users
     WHERE id = :id'
);

$stmt->execute([
    'id' => $userId
]);

$user = $stmt->fetch();

PDO Fetch Multiple Rows

$stmt = $pdo->query(
    'SELECT id, name
     FROM users
     ORDER BY name'
);

$users = $stmt->fetchAll();

PDO Insert

$stmt = $pdo->prepare(
    'INSERT INTO users (name, email)
     VALUES (:name, :email)'
);

$stmt->execute([
    'name' => $name,
    'email' => $email,
]);

$newId = $pdo->lastInsertId();

PDO Transaction

try {
    $pdo->beginTransaction();

    // Multiple related database changes

    $pdo->commit();

} catch (Throwable $e) {

    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    throw $e;
}

Transactions are essential when multiple database operations must succeed or fail as one logical operation.

JSON Encode

$json = json_encode(
    $data,
    JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
);

JSON Decode

$data = json_decode(
    $json,
    true,
    flags: JSON_THROW_ON_ERROR
);

Using JSON_THROW_ON_ERROR makes invalid JSON easier to handle with normal exception logic.

Return JSON From An API

header('Content-Type: application/json; charset=utf-8');

http_response_code(200);

echo json_encode([
    'success' => true,
    'data' => $result,
], JSON_THROW_ON_ERROR);

Common HTTP Status Codes

  • 200: Request Successful.
  • 201: Resource Created.
  • 204: Success With No Response Body.
  • 400: Bad Request.
  • 401: Authentication Required Or Invalid.
  • 403: Authenticated But Forbidden.
  • 404: Resource Not Found.
  • 409: Resource Conflict.
  • 422: Validation Error.
  • 429: Too Many Requests.
  • 500: Unexpected Server Error.

Read Raw JSON Request Data

$body = file_get_contents('php://input');

$data = json_decode(
    $body,
    true,
    flags: JSON_THROW_ON_ERROR
);

HTTP Headers In PHP

header('Content-Type: application/json');

header('Cache-Control: no-store');

header('X-Content-Type-Options: nosniff');

Headers must generally be sent before response body output begins.

Redirects

header('Location: /dashboard', true, 302);
exit;

For permanent redirects:

header('Location: /new-page', true, 301);
exit;

File Reading And Writing

$content = file_get_contents('/path/file.txt');

file_put_contents('/path/file.txt', $content);

Append:

file_put_contents(
    '/path/log.txt',
    $line,
    FILE_APPEND | LOCK_EX
);

Check Files And Directories

file_exists($path);

is_file($path);

is_dir($path);

is_readable($path);

is_writable($path);

Path Utilities

basename($path);

dirname($path);

pathinfo($path);

realpath($path);

Never pass raw user input directly into filesystem functions without validation and authorization.

Secure Random Values

Generate security-sensitive random bytes with:

$token = bin2hex(random_bytes(32));

Do not use rand() or mt_rand() for password reset tokens, CSRF secrets, or authentication credentials.

Password Hashing

$hash = password_hash(
    $password,
    PASSWORD_DEFAULT
);

Verify:

if (password_verify($password, $hash)) {
    // Password is correct
}

Check whether the hash should be upgraded:

if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
    $hash = password_hash($password, PASSWORD_DEFAULT);
}

HTML Output Escaping

echo htmlspecialchars(
    $value,
    ENT_QUOTES | ENT_SUBSTITUTE,
    'UTF-8'
);

Use output encoding based on the destination context rather than attempting to “sanitize everything” once globally.

Input Validation

Validate An Email

$email = filter_var(
    $input,
    FILTER_VALIDATE_EMAIL
);

if ($email === false) {
    // Invalid
}

Validate An Integer

$id = filter_var(
    $input,
    FILTER_VALIDATE_INT
);

Validate A URL

$url = filter_var(
    $input,
    FILTER_VALIDATE_URL
);

Application-specific business validation is still required after basic format validation.

Sessions

Start a session:

session_start();

Store a value:

$_SESSION['user_id'] = $userId;

Read it:

$userId = $_SESSION['user_id'] ?? null;

Regenerate the session ID after login:

session_regenerate_id(true);

Secure Session Cookie Setup

ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

session_start();

Destroy A Session

$_SESSION = [];

session_destroy();

Depending on the application, also clear the session cookie during logout.

CSRF Token Pattern

$_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));

Validate:

$token = $_POST['csrf_token'] ?? '';

if (!hash_equals($_SESSION['csrf_token'], $token)) {
    http_response_code(403);
    exit('Invalid request.');
}

Date And Time Basics

Prefer immutable date objects for many business workflows.

$now = new DateTimeImmutable();

echo $now->format('Y-m-d H:i:s');

Specific timezone:

$timezone = new DateTimeZone('Asia/Karachi');

$now = new DateTimeImmutable(
    'now',
    $timezone
);

Common Date Format Characters

  • Y: Four-Digit Year.
  • m: Numeric Month.
  • d: Day.
  • H: 24-Hour Format.
  • i: Minutes.
  • s: Seconds.
  • c: ISO 8601 Date.

Date Arithmetic

$tomorrow = $now->modify('+1 day');

$nextMonth = $now->modify('+1 month');

Or use intervals:

$future = $now->add(
    new DateInterval('P7D')
);

Environment Variables

$dbHost = getenv('DB_HOST');

Environment variables can keep deployment-specific configuration outside source files, although production secret management requires appropriate infrastructure and access controls.

Never expose private server credentials to frontend JavaScript.

Composer Basics

Initialize a project:

composer init

Install a package:

composer require vendor/package

Install development-only tooling:

composer require --dev phpunit/phpunit

Install locked dependencies:

composer install

Update dependencies:

composer update

Regenerate autoload files:

composer dump-autoload

Composer Autoloading

Include the Composer autoloader:

require __DIR__ . '/vendor/autoload.php';

A typical PSR-4 configuration inside composer.json might look like:

{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

Then run:

composer dump-autoload

Composer Security Audit

Modern PHP projects should audit dependencies:

composer audit

The Composer audit command can identify packages affected by known security advisories and can also report other dependency policy concerns such as abandoned or malware-flagged packages.

Include dependency auditing in CI/CD rather than relying entirely on occasional manual checks.

Namespaces

namespace App\Services;

class InvoiceService
{
}

Import classes with:

use App\Services\InvoiceService;

Alias:

use App\Services\InvoiceService as Invoices;

Useful Magic Constants

__FILE__

__DIR__

__LINE__

__CLASS__

__METHOD__

__FUNCTION__

__NAMESPACE__

Example:

require __DIR__ . '/config.php';

__DIR__ is particularly useful for reliable filesystem paths.

Useful Superglobals

  • $_GET — Query Parameters.
  • $_POST — Form Data.
  • $_FILES — Uploaded Files.
  • $_COOKIE — Cookies.
  • $_SESSION — Session Data.
  • $_SERVER — Server And Request Information.
  • $_ENV — Environment Data Where Configured.

Every request-derived superglobal should be considered untrusted input.

Useful Server Variables

$_SERVER['REQUEST_METHOD'] ?? '';

$_SERVER['REQUEST_URI'] ?? '';

$_SERVER['HTTP_USER_AGENT'] ?? '';

$_SERVER['REMOTE_ADDR'] ?? '';

Do not automatically trust forwarded IP headers unless your reverse proxy infrastructure is configured to provide them securely.

Request Method Check

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

Simple API Router Pattern

$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url(
    $_SERVER['REQUEST_URI'],
    PHP_URL_PATH
);

if ($method === 'GET' && $path === '/api/users') {
    // List users
}

For larger applications, use a structured router or framework rather than growing a massive chain of conditions.

File Upload Checks

Always inspect upload errors first:

if (
    !isset($_FILES['image']) ||
    $_FILES['image']['error'] !== UPLOAD_ERR_OK
) {
    throw new RuntimeException('Upload failed.');
}

Generate your own filename:

$filename = bin2hex(random_bytes(16)) . '.jpg';

Never trust the client filename or MIME header as your only validation.

Useful File Upload Constants

  • UPLOAD_ERR_OK
  • UPLOAD_ERR_INI_SIZE
  • UPLOAD_ERR_FORM_SIZE
  • UPLOAD_ERR_PARTIAL
  • UPLOAD_ERR_NO_FILE

Regular Expressions

Test a pattern:

if (preg_match('/^[A-Z0-9_-]+$/i', $username)) {
    // Match
}

Replace:

$result = preg_replace(
    '/\s+/',
    ' ',
    $text
);

Do not use regular expressions for problems where a proper parser or built-in validator is safer.

Generators

Generators can produce values lazily without loading every item into memory at once.

function numbers(int $max): Generator
{
    for ($i = 1; $i <= $max; $i++) {
        yield $i;
    }
}

Usage:

foreach (numbers(1000000) as $number) {
    // Process one value at a time
}

This can be valuable when processing large datasets or streams.

Fibers

Fibers provide low-level support for interruptible functions and are mainly useful as infrastructure for asynchronous libraries and frameworks.

Most application developers do not need to manually build ordinary CRUD applications around Fibers.

Use them when your architecture or chosen asynchronous library genuinely requires cooperative execution.

PHP CLI Basics

Execute a script:

php script.php

Run inline PHP:

php -r "echo PHP_VERSION;"

Start PHP’s built-in development server:

php -S localhost:8000

The built-in server is useful for local development and testing, not as a production web server.

CLI Arguments

print_r($argv);

The number of arguments is available through:

echo $argc;

Error Logging

error_log('Unexpected payment failure');

Production servers should typically log detailed errors without displaying them publicly.

Conceptually:

display_errors = Off
log_errors = On

Useful Debugging Functions

var_dump($value);

print_r($array);

These are valuable during development, but do not leave sensitive debugging output exposed in production pages.

Assertions

assert($total >= 0);

Assertions can be useful for development assumptions, but business validation and security rules must not depend solely on assertions that may be disabled or configured differently.

HTTP Requests With cURL

$ch = curl_init('https://api.example.com/users');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
]);

$response = curl_exec($ch);

curl_close($ch);

For large applications, a mature HTTP client package can provide cleaner abstractions, retries, middleware, and better testing support.

URL Encoding

$value = urlencode($text);

$query = http_build_query([
    'page' => 2,
    'search' => 'PHP developer',
]);

Hashing

$hash = hash(
    'sha256',
    $data
);

Use general-purpose hashes for appropriate integrity or fingerprinting needs, not for password storage.

HMAC

$signature = hash_hmac(
    'sha256',
    $payload,
    $secret
);

Use HMAC for appropriate message authentication scenarios such as webhook signing when compatible with the protocol.

Compare signatures with:

hash_equals(
    $expectedSignature,
    $receivedSignature
);

Never Use These Legacy Patterns

  • mysql_* Functions: Removed long ago; use PDO or MySQLi.
  • MD5 For Passwords: Use password_hash().
  • SHA1 For Passwords: Use password_hash().
  • String-Concatenated SQL: Use prepared statements.
  • Addslashes As SQL Protection: It is not a replacement for prepared queries.
  • Magic Quotes Thinking: Long obsolete.
  • Short Open Tags As A Portability Assumption: Use the standard PHP opening tag.
  • Dynamic Properties Everywhere: Prefer declared properties and modern class design.
  • Global Variables For Application Architecture: Use explicit dependencies and structured services.

Modern PHP Project Structure

A small structured application might use:

project/
├── composer.json
├── composer.lock
├── config/
├── public/
│   └── index.php
├── src/
│   ├── Controllers/
│   ├── Services/
│   ├── Repositories/
│   └── Domain/
├── storage/
│   └── logs/
├── tests/
└── vendor/

Only the public directory should normally be directly exposed by the web server.

PHP Security Quick Reference

  • SQL Injection: Use Prepared Statements.
  • XSS: Encode Output For Its Context.
  • CSRF: Verify Cryptographically Random Tokens.
  • Passwords: Use Password_Hash And Password_Verify.
  • Sessions: Use Secure, HttpOnly, SameSite, And Strict Mode.
  • Authorization: Check Every Sensitive Object And Action.
  • Uploads: Validate Type, Size, Name, Storage, And Execution.
  • Secrets: Keep Them Outside Public Files And Source Control.
  • Dependencies: Run Composer Audit.
  • Runtime: Use A Supported Patched PHP Version.

PHP Performance Quick Reference

  • Enable OPcache In Production.
  • Index Frequently Queried Database Columns.
  • Avoid N+1 Database Queries.
  • Cache Expensive Repeated Results.
  • Paginate Large Datasets.
  • Move Heavy Work To Background Jobs.
  • Profile Before Optimizing.

Do not micro-optimize simple syntax while a slow database query consumes most of the request time.

Useful PHP Development Commands

php -v

php -m

php --ini

php -l file.php

php -S localhost:8000

composer install

composer update

composer dump-autoload

composer audit

Syntax-check a PHP file with:

php -l app.php

This is useful inside automated checks and deployment workflows.

PHP Developer Workflow For 2026

  1. Use A Supported PHP Version.
  2. Enable Strict Types Where Appropriate.
  3. Use Composer And PSR-4 Autoloading.
  4. Write Typed Classes And Functions.
  5. Use Enums For Finite Domain States.
  6. Use PDO Prepared Statements.
  7. Build Explicit Authentication And Authorization.
  8. Add Automated Tests And Static Analysis.
  9. Run Composer Audit In CI/CD.
  10. Log Errors Privately And Monitor Production.

Ultimate PHP Cheat Sheet Checklist

  • Syntax: Variables, Constants, Operators, Conditionals, And Loops.
  • Types: Scalar, Union, Nullable, And Return Types.
  • Arrays: Map, Filter, Reduce, Spread, And Destructuring.
  • Strings: Standard And Multibyte Functions.
  • Functions: Closures, Arrow Functions, Variadics, And Named Arguments.
  • OOP: Classes, Interfaces, Traits, Abstract Classes, And Readonly Objects.
  • Modern PHP: Enums, Attributes, Match, Nullsafe Access, Property Hooks, And Pipe Operator.
  • Database: PDO, Prepared Statements, Fetching, Inserts, And Transactions.
  • Web APIs: JSON, HTTP Status Codes, Headers, And Request Bodies.
  • Security: Passwords, Sessions, CSRF, XSS, SQL Injection, And Secure Randomness.
  • Tooling: Composer, Autoloading, CLI, Dependency Auditing, And CI/CD.
  • Production: OPcache, Logging, HTTPS, Error Handling, And Supported PHP Versions.

Final Verdict On Modern PHP Development In 2026

PHP in 2026 is a modern backend language with a much richer feature set than the PHP many developers first learned years ago.

The foundational syntax remains approachable. Variables, arrays, loops, functions, forms, and database access can still be learned quickly, which is one reason PHP remains productive for web development.

But professional PHP now goes far beyond those basics.

Strict typing, typed properties, union types, constructor property promotion, enums, attributes, match expressions, null-safe access, readonly objects, static analysis, Composer autoloading, and modern framework ecosystems allow teams to build structured applications rather than collections of procedural scripts.

PHP 8.4 added particularly useful object-model improvements such as property hooks and asymmetric property visibility. These capabilities can reduce repetitive getters and setters while allowing developers to express domain rules more directly.

PHP 8.5 continues that evolution with the pipe operator, modern URI support, #[\NoDiscard], clone enhancements, and other language improvements.

At the database layer, PDO prepared statements should be standard practice. Directly concatenating request data into SQL belongs in legacy code, not modern PHP applications.

At the security layer, use PHP’s dedicated APIs.

Passwords belong in password_hash() and password_verify(). Security tokens should come from random_bytes(). Sensitive comparisons can use hash_equals(). HTML output should be encoded correctly for its context.

At the application architecture layer, avoid giant files containing HTML, SQL, authentication, business rules, and routing simultaneously.

Separate responsibilities into services, repositories, controllers, domain objects, templates, and reusable security controls where the project’s size justifies them.

At the dependency level, Composer is no longer optional tooling for serious PHP applications.

Use reproducible dependency installation, commit the application’s lock file, maintain PSR-4 autoloading, and run composer audit to detect known dependency security issues.

At the production level, use supported PHP versions, OPcache, HTTPS, appropriate logging, private error details, backups, monitoring, and properly configured infrastructure.

Finally, do not measure PHP expertise by how many functions you can memorize.

The better developer knows which primitives exist, understands their correct use, recognizes unsafe legacy patterns, and knows how to find the exact detail when it matters.

The Ultimate PHP Cheat Sheet For 2026 Is Therefore A Mental Model As Much As A Reference: Use Modern Types, Express Domain Rules Clearly, Prefer Standard APIs, Parameterize Data Access, Protect Trust Boundaries, Manage Dependencies Professionally, And Keep The Runtime Current.

Everyday Reader Frequently Asked Questions

What PHP Features Should Every Developer Know In 2026?

Every PHP developer should understand strict types, arrays, functions, closures, OOP, interfaces, traits, enums, attributes, match expressions, null-safe access, readonly objects, PDO prepared statements, JSON, exceptions, sessions, password APIs, Composer, autoloading, and core web-security practices. Developers using PHP 8.4 and 8.5 should also understand newer capabilities such as property hooks, asymmetric visibility, and the pipe operator.

Which PHP Version Should I Learn In 2026?

Learn modern PHP 8.x syntax rather than targeting obsolete PHP 7 or older code. For new projects, use a currently supported release compatible with your dependencies. PHP 8.5 is the newest major branch in 2026, while PHP 8.4 also remains actively supported and widely relevant.

What Is The Best Way To Connect PHP To MySQL?

PDO is a strong general-purpose choice because it provides a consistent object-oriented interface and supports prepared statements. Configure PDO to throw exceptions, use UTF-8 such as utf8mb4 for MySQL connections, and always parameterize untrusted values rather than concatenating them into SQL strings.

What PHP Security Functions Should Every Developer Know?

Important functions and APIs include password_hash(), password_verify(), password_needs_rehash(), random_bytes(), hash_equals(), htmlspecialchars(), filter_var(), PDO prepared statements, session_regenerate_id(), and secure session cookie configuration. These functions should be combined with authorization, HTTPS, safe file handling, and dependency security.

Is PHP Still Worth Learning In 2026?

Yes. PHP remains actively developed and supports modern language features, object-oriented programming, APIs, web applications, CMS platforms, SaaS products, and backend services. Its mature ecosystem, Composer dependency management, widespread hosting support, Laravel and Symfony frameworks, and continued PHP 8.x development make it a practical backend skill in 2026.

YOU LIKE IT? PLEASE SHARE THIS RECIPE WITH YOUR FRIENDS

Be the first to write a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *