PHP: reference

The web's server-side language: variables, arrays, functions and safe form handling.

Basics

The first script

PHP code sits between <?php and ?>. Every statement ends with a semicolon.

<?php
echo "Hello, world!";
echo 2 + 3;
// comment
# also a comment
/* multi-line */

Running

PHP runs on the server, and the browser receives ready HTML.

php index.php            # in the terminal
php -S localhost:8000    # built-in server

Variables and types

Variables

Variable names start with the $ sign. Double quotes insert variable values, single quotes do not.

$name = "Alex";
$age = 16;
$price = 24.5;
$ok = true;
$nothing = null;
echo "Hello, $name! You are {$age} years old.";
var_dump($age);

Constants and operations

Strings are joined with a dot ., not a plus.

const SITE = "Iteris";
define("VERSION", "1.0");
echo 7 % 2, 2 ** 10, intdiv(7, 2);
echo "Sum: " . (2 + 3);

Conditions and loops

if and match

Compare with ===: it checks the type as well.

if ($age < 12) {
    echo "child";
} elseif ($age < 18) {
    echo "teenager";
} else {
    echo "adult";
}
$kind = match (true) {
    $age < 18 => "minor",
    default => "adult",
};

Loops

For arrays foreach is usually used.

for ($i = 0; $i < 3; $i++) {
    echo $i;
}
while ($n < 3) { $n++; }
foreach ([10, 20, 30] as $x) {
    echo $x;
}

Arrays

Indexed array

$a[] = x adds an element to the end.

$nums = [3, 1, 2];
$nums[] = 5;
sort($nums);
echo count($nums), $nums[0];
echo implode(", ", $nums);

Associative array

The ?? operator returns a fallback value if the key is missing.

$user = ["name" => "Alex", "age" => 16];
$user["city"] = "Dnipro";
echo $user["name"] ?? "none";
foreach ($user as $key => $value) {
    echo "$key: $value\n";
}

Strings

String functions

For Ukrainian text use the functions with the mb_ prefix.

$s = "PHP language";
echo strlen($s), strtoupper($s), str_replace("language", "rocks", $s);
echo mb_strlen($s), mb_substr($s, 0, 3);
echo trim("  hello  "), str_contains($s, "PHP");

Functions

Declaration

Parameter and return types are optional but make the code more reliable.

function add(int $a, int $b = 0): int {
    return $a + $b;
}
echo add(2, 3);
$sq = fn($x) => $x * $x;
echo $sq(4);

Forms and requests

Handling POST safely

Always escape data from forms with htmlspecialchars before printing it into HTML: this protects against XSS.

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name = trim($_POST["name"] ?? "");
    if ($name === "") {
        echo "Enter a name";
    } else {
        echo "Hello, " . htmlspecialchars($name);
    }
}

GET and sessions

$_GET holds the URL parameters, $_SESSION holds user data between requests.

$page = (int)($_GET["page"] ?? 1);
session_start();
$_SESSION["user"] = "Alex";

Classes

Class and method

-> is used to access the fields and methods of an object.

class Dog {
    public function __construct(private string $name) {}

    public function speak(): string {
        return "{$this->name}: woof!";
    }
}
$rex = new Dog("Rex");
echo $rex->speak();

Database (PDO)

Prepared statements

Never insert user data directly into SQL: use prepare and execute.

$pdo = new PDO("sqlite:app.db");
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

Errors

try / catch

An exception is thrown with throw and caught in catch.

try {
    if ($b === 0) throw new InvalidArgumentException("Division by zero");
    echo $a / $b;
} catch (InvalidArgumentException $e) {
    echo $e->getMessage();
}

Learn PHP with practice

Want to learn step by step? Your account has 110 lessons organised by chapter (80 core and 30 advanced, you can switch the level at any time) and tasks with code checking.