← Back to Index

PHP Reference

0. Basics

0.1 Hello World

<?php
// echo prints strings to STDOUT
echo "Hello, World!\n";
TERMINAL OUTPUT
Hello, World!

0.2 Building & Running

PHP is interpreted. Run scripts directly using the php CLI.

# Execute a PHP script from the terminal
php main.php
TERMINAL OUTPUT
Hello, World!

0.3 Comments

// Single-line comment
# Also a single-line comment (shell-style)
/* Multi-line
   comment block for longer explanations */
TERMINAL OUTPUT
(No output)

0.4 Imports

require 'file.php';      // Stop execution if file is missing
require_once 'file.php'; // Include only once per script execution
include 'file.php';      // Emit warning if file is missing, but continue
TERMINAL OUTPUT
(No output)

0.5 Exit Codes

// Terminate script with status: 0 for success, 1-255 for error
exit(1); 

// Print message and exit with status 1
// die("Fatal Error!"); 
TERMINAL OUTPUT
(Process exits with status 1)

0.6 Error Handling

try {
    // Explicitly throw a new Exception
    throw new Exception("failed");
} catch (Throwable $e) {
    // Catch any Throwable (Exception or Error) and print message
    echo $e->getMessage();
} finally {
    // Always runs after try/catch
    echo "Cleanup";
}
TERMINAL OUTPUT
failedCleanup

1. Environment, Variables & Time

1.1 Variable Declaration

PHP variables must start with a $.

$x = 5;          // Mutable variable
$name = "PHP";   // String variable
define("MAX_VAL", 100); // Define a global constant
const MIN_VAL = 1;      // Define a compile-time constant
TERMINAL OUTPUT
(No output)

1.2 Integer Types & Limits

Integers are signed and size is platform-dependent (usually 64-bit).

// Max value for integers on this platform
echo PHP_INT_MAX; 
// Integer size in bytes
echo PHP_INT_SIZE; 
TERMINAL OUTPUT
9223372036854775807 (example)
8 (example)

1.3 Casting

Use type names in parentheses for explicit casting.

$i = (int)3.14;       // Float to integer (3)
$f = (float)"1.23";   // String to float (1.23)
$s = (string)100;     // Integer to string ("100")
$b = (bool)1;         // Integer to boolean (true)
TERMINAL OUTPUT
(No output)

1.4 Environment Variables

// Retrieve environment variable
$val = getenv("PATH");
// Set environment variable for the current request
putenv("API_KEY=secret");
// Access via superglobal array
$_ENV["KEY"] = "VALUE";
TERMINAL OUTPUT
(No output)

1.5 Time Measurement & Formatting

// Performance measurement in fractional seconds (float)
$start = microtime(true);
$elapsed = microtime(true) - $start;

// Time formatting using DateTime object
$now = new DateTime();
echo $now->format(DateTime::ATOM); // ISO 8601 format
TERMINAL OUTPUT
2024-05-16T12:00:00+00:00 (example)

2. Operators & Regex

2.1 Arithmetic & Logic

$a = 10 / 3;   // Standard division returns float (3.333)
$b = intdiv(10, 3); // Integer division (3)
$c = 10 ** 3;  // Exponentiation (1000)
$d = true && false; // Logical AND (false)
TERMINAL OUTPUT
(No output)

2.2 Regex & Pattern Matching

Using PCRE preg_ functions.

$text = "The price is $100";
// Perform regex match and capture groups into $matches
if (preg_match('/\$(\d+)/', $text, $matches)) {
    echo $matches[1]; // Print first capture group: "100"
}
TERMINAL OUTPUT
100

3. Argument Parsing

3.1 Argument Parsing

// Parse CLI options: v (flag), output (requires value)
$options = getopt("v", ["output:"]);

$verbose = isset($options['v']);
$output = $options['output'] ?? 'default.txt';
// echo $output;
TERMINAL OUTPUT
(No output)

4. Functions & Memory

4.1 Declaration & Returns

// Basic function with type hints and default value
function add(int $a, int $b = 0): int {
    return $a + $b;
}

// Multi-return via Array destructuring
function getStatus(): array {
    return [200, "OK"];
}
[$code, $msg] = getStatus();
TERMINAL OUTPUT
(No output)

4.2 References & Pointers

// Use & to pass a variable by reference
function increment(&$n) {
    $n++; // Modifies the original variable value
}

$val = 10;
increment($val); // $val is now 11
TERMINAL OUTPUT
(No output)

5. Control Flow

5.1 Conditionals (If/Else)

Standard branching logic. PHP uses if, elseif, and else.

$x = 10;
if ($x > 5) {
    echo "Greater";
} elseif ($x == 5) {
    echo "Equal";
} else {
    echo "Less";
}
TERMINAL OUTPUT
Greater

5.2 Switch / Case

PHP uses switch or the modern match (PHP 8.0+) for multi-way branching.

$val = 2;
switch ($val) {
    case 1:
        echo "One";
        break;
    case 2:
    case 3:
        echo "Two or Three";
        break;
    default:
        echo "Other";
}

// PHP 8.0+ match expression
$res = match ($val) {
    1 => "One",
    2, 3 => "Two or Three",
    default => "Other",
};
TERMINAL OUTPUT
Two or Three

5.3 Basic Loops (While/For)

Iterative execution using for, while, or do-while.

// for loop (0 to 2)
for ($i = 0; $i < 3; $i++) {
    echo "for: $i ";
}

$x = 0;
while ($x < 3) {
    echo "while: $x ";
    $x++;
}
TERMINAL OUTPUT
for: 0 for: 1 for: 2 while: 0 while: 1 while: 2 

5.4 Breaking & Continue

Controlling loop flow.

foreach ([0, 1, 2, 3, 4, 5] as $val) {
    if ($val < 2) continue; // Skip iteration
    if ($val == 5) break;    // Exit loop
    echo "$val ";
}
TERMINAL OUTPUT
2 3 4 

5.5 Iterating Collections

Accessing items in indexed or associative arrays using foreach.

// Indexed Array iteration
foreach (['a', 'b'] as $val) {
    echo "val: $val ";
}

// Associative Array (Map) iteration
foreach (['id' => 42] as $key => $val) {
    echo "$key: $val";
}
TERMINAL OUTPUT
val: a val: b id: 42

6. Strings & Files

6.1 String Manipulation

$s = " Hello ";
$s = trim($s); // Remove whitespace: "Hello"
$sub = substr($s, 0, 2); // Result: "He"
$joined = implode("-", ["a", "b"]); // Result: "a-b"
TERMINAL OUTPUT
(No output)

6.2 Path Joining

// Join path segments using the system's directory separator
$p = implode(DIRECTORY_SEPARATOR, ["", "usr", "bin"]);
TERMINAL OUTPUT
(No output)

6.3 Streaming I/O (Chunks)

// Open file handle for reading
$f = fopen("data.bin", "rb");
while (!feof($f)) {
    // Read 4KB chunk from stream
    $chunk = fread($f, 4096);
}
fclose($f);
TERMINAL OUTPUT
(No output)

6.4 Read to Memory

// Read entire file content into a string
$content = @file_get_contents("file.txt");

// Read entire file into an array of lines
$lines = @file("file.txt");
TERMINAL OUTPUT
(No output)

7. Binary & Bitwise

7.1 Allocation & Packing

PHP uses pack for binary buffer creation.

// Pack values into binary string: N (32-bit BE), E (64-bit float BE)
$buf = pack("NE", 42, 3.14);

// Unpack binary string into associative array
$data = unpack("Ni/Ef", $buf);
$i = $data['i']; $f = $data['f'];
TERMINAL OUTPUT
(No output)

7.2 Bitwise Operations

$res = 0b1010 & 0b1100; // Bitwise AND
$res = 0b1010 | 0b1100; // Bitwise OR
$res = 0b1010 ^ 0b1100; // Bitwise XOR
$res = ~0b1010;         // Bitwise NOT (complement)
$res = 0b0001 << 2;     // Bitwise Shift Left (0b0100)
TERMINAL OUTPUT
(No output)

7.3 Hex Conversion

// Decimal to Hex
$s = dechex(255); // "ff"
// Hex to Decimal
$val = hexdec("ff"); // 255
TERMINAL OUTPUT
(No output)

8. Collections & JSON

8.1 Lists, Maps & Sets

The PHP array is a multi-purpose ordered map.

$l = [1, 2]; $l[] = 3; // Indexed Array (List)
$m = ["k" => "v"];     // Associative Array (Map)
$s = array_unique([1, 1, 2]); // Unique values behavior
TERMINAL OUTPUT
(No output)

8.2 JSON Parsing

// Decode JSON string into associative array (true)
$data = json_decode('{"id": 42}', true);
// Encode associative array to JSON string
$s = json_encode($data);
TERMINAL OUTPUT
(No output)

9. Systems & Networking

9.1 TCP Server & Client

Requires the sockets extension.

// Create and bind a TCP socket
$srv = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
@socket_bind($srv, '0.0.0.0', 8080); 

// Create and connect a TCP client socket
$cli = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
@socket_connect($cli, "example.com", 80);
@socket_write($cli, "GET / HTTP/1.0\r\n\r\n");
TERMINAL OUTPUT
(No output)

9.2 UDP Server & Client

// Create UDP socket
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
// Send datagram to address:port
@socket_sendto($s, "ping", 4, 0, "127.0.0.1", 8080);
TERMINAL OUTPUT
(No output)

9.3 Concurrency

// Fork the current process (CLI only)
$pid = pcntl_fork();
if ($pid == 0) {
    // Child process context
    echo "In child";
    exit(0);
}
// Parent process waits for child to finish
pcntl_wait($status);
TERMINAL OUTPUT
In child

9.4 SQLite

// Open/Create SQLite3 database in memory
$db = new SQLite3(':memory:');
// Execute SQL statement
$db->exec("CREATE TABLE t(id)");
// Query and fetch single value
echo $db->querySingle("SELECT 42");
TERMINAL OUTPUT
42