← All guides

Programmer’s Reference

PHP

Build reliable server-side pages, APIs, and database tools.

PHP 8.x. CLI commands go in a terminal; PHP examples go in a .php file. No private application endpoints or secrets are included.

26 entries · Essentials first · Reviewed October 5, 2026

Glossary: commands, keywords & terms

Select a term for its definition, syntax, example, and common mistakes.

Keywords and syntax

if / elseif / else

Choose which block executes by testing conditions.

PHP code
<?php
$count = 3;
if ($count > 5) {
    echo 'Many';
} elseif ($count > 0) {
    echo 'Some';
} else {
    echo 'None';
}

Practical useUse this construct in your own practice project.

Common mistakesUse == or === for comparison; = assigns a value.

Source: www.php.net documentation

or / ||

Logical OR succeeds if either operand is true; evaluation short-circuits.

PHP code
<?php
$cached = false;
$ready = true;
$available = ($cached || $ready);
echo $available ? 'Available' : 'Unavailable';

Practical useUse this construct in your own practice project.

Common mistakesor has lower precedence than assignment; parenthesize expressions or use || deliberately.

Source: www.php.net documentation

and / &&

Logical AND requires both operands to be true.

PHP code
<?php
$signedIn = true;
$allowed = false;
if ($signedIn && $allowed) { echo 'Allowed'; }

Practical useUse this construct in your own practice project.

Common mistakesCheck operator precedence; do not substitute bitwise & for &&.

Source: www.php.net documentation

! (NOT)

Negate a boolean condition.

PHP code
<?php
$ready = false;
if (!$ready) { echo 'Waiting'; }

Practical useUse this construct in your own practice project.

Common mistakesUse parentheses when negating a compound condition.

Source: www.php.net documentation

for

Repeat a block using initialization, a condition, and an update.

PHP code
<?php
for ($i = 0; $i < 3; $i++) {
    echo $i . PHP_EOL;
}

Practical useUse this construct in your own practice project.

Common mistakesEnsure the update eventually makes the condition false.

Source: www.php.net documentation

foreach

Visit each value, optionally with its key, in an iterable.

PHP code
<?php
foreach (['name' => 'Demo', 'state' => 'Ready'] as $key => $value) {
    echo $key . ': ' . $value . PHP_EOL;
}

Practical useUse this construct in your own practice project.

Common mistakesReferences using & can remain bound after a loop; unset them when needed.

Source: www.php.net documentation

while

Repeat while the condition is true, testing before each iteration.

PHP code
<?php
$attempt = 0;
while ($attempt < 3) {
    echo ++$attempt;
}

Practical useUse this construct in your own practice project.

Common mistakesUpdate the condition to avoid an infinite loop.

Source: www.php.net documentation

do / while

Execute the body at least once, then test whether to repeat.

PHP code
<?php
$attempt = 0;
do {
    $attempt++;
} while ($attempt < 3);

Practical useUse this construct in your own practice project.

Common mistakesThe trailing semicolon after while is required.

Source: www.php.net documentation

break

Exit the enclosing loop or switch early.

PHP code
<?php
foreach ([1, 2, 3] as $n) {
    if ($n === 2) { break; }
    echo $n;
}

Practical useUse this construct in your own practice project.

Common mistakesbreak does not return from a function. Numeric levels can exit multiple enclosing structures.

Source: www.php.net documentation

continue

Skip the rest of the current loop iteration.

PHP code
<?php
foreach ([1, 2, 3] as $n) {
    if ($n === 2) { continue; }
    echo $n;
}

Practical useUse this construct in your own practice project.

Common mistakesInside switch, continue has special behavior; consult the nesting rules.

Source: www.php.net documentation

switch / case / default

Select a branch using loose comparisons against case values.

PHP code
<?php
$state = 'ready';
switch ($state) {
    case 'ready': echo 'Ready'; break;
    default: echo 'Unknown';
}

Practical useUse this construct in your own practice project.

Common mistakesMissing break can fall through into the next case; comparisons are loose.

Source: www.php.net documentation

match

PHP 8+: return a value from a branch using strict identity comparisons.

PHP code
<?php
$state = 'ready';
$label = match ($state) {
    'ready' => 'Ready',
    default => 'Unknown',
};
echo $label;

Practical useUse this construct in your own practice project.

Common mistakesUnlike switch, match is an expression with strict comparison and no fallthrough.

Source: www.php.net documentation

return

End a function and provide its result to the caller.

PHP code
<?php
function doubleValue(int $n): int {
    return $n * 2;
}
echo doubleValue(3);

Practical useUse this construct in your own practice project.

Common mistakesCode after an unconditional return in the same block is unreachable.

Source: www.php.net documentation

goto / label

Jump to a named label within the permitted file and execution context.

PHP code
<?php
goto finished;
echo 'Skipped';
finished:
echo 'Finished';

Practical useUse this construct in your own practice project.

Common mistakesLabels are case-sensitive. You cannot jump into a loop/switch or across function boundaries; structured control flow is usually clearer.

Source: www.php.net documentation

try / catch / finally / throw

Throw an exception, handle a matching type, and execute cleanup.

PHP code
<?php
try {
    throw new RuntimeException('Demo error');
} catch (RuntimeException $error) {
    echo 'Handled';
} finally {
    echo 'Cleanup';
}

Practical useUse this construct in your own practice project.

Common mistakesCatch expected types and avoid exposing confidential error messages to visitors.

Source: www.php.net documentation

?? (null coalescing)

Use a fallback when a value is absent or null.

PHP code
<?php
$settings = [];
$name = $settings['name'] ?? 'Demo';
echo $name;

Practical useUse this construct in your own practice project.

Common mistakesFalse, zero, and an empty string do not trigger this fallback.

Source: www.php.net documentation

Essentials

Run and check PHP

Show the interpreter version, then check a file for syntax errors without executing it.

Terminal
php --version
php -l example.php

Practical useLint a proposed your application page before staging it.

Common mistakesA successful lint does not verify application behavior. CLI and web PHP can use different versions and configuration.

Source: www.php.net documentation

Variables and output

Store a value and render text. Escape dynamic HTML before inserting it into a page.

PHP code
<?php
$name = 'Demo site';
echo '<h1>' . htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</h1>';

Practical useRender a website label safely in an application table.

Common mistakesDo not output raw user input. HTML escaping is context-specific; it is not SQL escaping.

Source: www.php.net documentation

Arrays and foreach

Use associative arrays for named fields and foreach to visit records.

PHP code
<?php
$sites = [['name' => 'Demo', 'enabled' => true]];
foreach ($sites as $site) {
    echo htmlspecialchars($site['name'], ENT_QUOTES, 'UTF-8') . PHP_EOL;
}

Practical useIterate a sanitized website inventory.

Common mistakesCheck that a key exists before reading it; an array is not automatically an object.

Source: www.php.net documentation

Functions and strict comparisons

Wrap repeatable logic in a typed function and compare types and values with ===.

PHP code
<?php
function serviceLabel(bool $running): string {
    return $running === true ? 'Running' : 'Stopped';
}
echo serviceLabel(true);

Practical useConvert a verified service-state value to a display label.

Common mistakesLoose == comparisons can convert types. Validate external input rather than assuming it is a boolean.

Source: www.php.net documentation

Forms and security

Validate request input

Validate an integer submitted in the query string and reject missing or invalid values.

PHP code
<?php
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === false || $id === null || $id < 1) {
    http_response_code(400);
    exit('Invalid id');
}

Practical useValidate a record selector before looking it up in your application.

Common mistakesValidation is not authorization. A valid record ID still needs permission checks.

Source: www.php.net documentation

Session and CSRF token

Create a random session-bound token to include in a POST form; compare it before accepting a state change.

PHP code
<?php
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf'] ?? '';
    if (!is_string($token) || !hash_equals($_SESSION['csrf'], $token)) {
        http_response_code(403);
        exit('Invalid token');
    }
}

Practical useUse the established application CSRF mechanism rather than adding a competing one.

Common mistakesThe form must submit the same token in a hidden field. This fragment does not implement login, cookie policy, or authorization.

Source: www.php.net documentation (1) · www.php.net documentation (2) · www.php.net documentation (3)

Hash and verify passwords

Create a one-way password hash and verify a supplied password against it.

PHP code
<?php
$hash = password_hash('demo-only-password', PASSWORD_DEFAULT);
$valid = password_verify('demo-only-password', $hash);

Practical useUse standard password APIs in an isolated login prototype.

Common mistakesNever use this demonstration password for an account. Store hashes, not plaintext; allow sufficient database column length.

Source: www.php.net documentation (1) · www.php.net documentation (2)

Files and APIs

Return JSON

Set the content type and encode a PHP value, throwing an exception if encoding fails.

PHP code
<?php
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['service' => 'demo', 'running' => true], JSON_THROW_ON_ERROR);

Practical useRepresent a sanitized service status response.

Common mistakesSend headers before output. Do not return exception traces or credentials to visitors.

Source: www.php.net documentation

Read a local JSON file

Load a fixed local fixture and decode it into an associative array.

PHP code
<?php
$text = file_get_contents(__DIR__ . '/demo-sites.json');
if ($text === false) { throw new RuntimeException('Cannot read fixture'); }
$sites = json_decode($text, true, 512, JSON_THROW_ON_ERROR);

Practical useRead a staging fixture instead of exposing live configuration.

Common mistakesDo not construct file paths from untrusted requests. Handle permissions and malformed JSON.

Source: www.php.net documentation (1) · www.php.net documentation (2)

Databases

Prepared database query

Bind a value to a prepared statement on an existing PDO connection. SQL and data stay separate.

PHP code
<?php
// $pdo is an authenticated PDO connection supplied by your application.
$stmt = $pdo->prepare('SELECT name FROM sites WHERE id = :id');
$stmt->execute(['id' => 7]);
$site = $stmt->fetch(PDO::FETCH_ASSOC);

Practical useLook up a site record after permission checks.

Common mistakesPlaceholders represent values, not table or column names. Check for false when no row is found.

Source: www.php.net documentation

Back to top ↑