PHP
Updated: May 22, 2026Categories: Languages, Frontend, Backend, Web
Printed from:
PHP Cheatsheet
Language Overview
PHP (Hypertext Preprocessor) is a popular server-side scripting language designed primarily for web development. Key characteristics include:
- Dynamic, gradually typed language with strong runtime type checks
- Embedded in HTML
- Runs on the server-side
- Widely used for web applications and backend development
- Supports object-oriented, procedural, and functional programming paradigms
- Current stable release: PHP 8.4 (with PHP 8.3 still actively supported; PHP 8.1 reached end-of-life in December 2025)
Basic Syntax
PHP
1234567891011121314<?php
// PHP code starts with <?php and ends with ?>
echo "Hello, World!"; // Print statement
// Single-line comment
# Also a single-line comment
/* Multi-line
comment */
// Semicolons are required to end statements
$variable = "Value"; // Variable declaration
// Strict typing (recommended at the top of every file)
declare(strict_types=1);
Data Types
Primitive Types
PHP
1234567891011121314151617181920212223// Integers
$int1 = 42;
$int2 = -17;
$int3 = 1_000_000; // Numeric literal separator (PHP 7.4+)
// Floating-point numbers
$float = 3.14;
// Strings
$str1 = 'Single quotes';
$str2 = "Double quotes with {$variable} interpolation";
$str3 = <<<EOT
Heredoc string with {$variable} interpolation
EOT;
// Booleans
$bool1 = true;
$bool2 = false;
// Null
$null_var = null;
// Resource (database connections, file handles)
$file_handle = fopen('example.txt', 'r');
Collection Types
PHP
12345678910111213141516171819202122// Indexed Array
$indexed_array = [1, 2, 3, 4, 5];
$indexed_array[] = 6; // Append
// Associative Array (key-value pairs)
$assoc_array = [
'name' => 'John',
'age' => 30,
'city' => 'New York'
];
// Multidimensional Array
$multi_array = [
'users' => [
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 30]
]
];
// Spread operator in arrays (PHP 8.1+ supports string keys)
$combined = [...$indexed_array, ...$assoc_array];
Variables and Constants
PHP
1234567891011121314151617181920212223// Variable declaration (dynamic typing)
$name = "John";
$age = 30;
// Type casting
$str_to_int = (int)"42";
$int_to_str = (string)42;
// Constants
define('APP_NAME', 'My PHP App');
const MAX_USERS = 100;
// Typed class constants (PHP 8.3+)
class Config {
const string VERSION = '1.0.0';
const int MAX_RETRIES = 3;
}
// Superglobal variables
echo $_SERVER['REQUEST_METHOD']; // HTTP request method
echo $_GET['param']; // GET parameters
echo $_POST['username']; // POST parameters
Operators
Arithmetic Operators
PHP
12345678910$a = 10;
$b = 3;
echo $a + $b; // Addition
echo $a - $b; // Subtraction
echo $a * $b; // Multiplication
echo $a / $b; // Division
echo $a % $b; // Modulus
echo $a ** $b; // Exponentiation
echo intdiv($a, $b); // Integer division
Comparison Operators
PHP
12345678910$a == $b; // Equal
$a === $b; // Identical (type and value)
$a != $b; // Not equal
$a !== $b; // Not identical
$a < $b; // Less than
$a > $b; // Greater than
$a <= $b; // Less than or equal
$a >= $b; // Greater than or equal
$a <=> $b; // Spaceship (returns -1, 0, or 1)
Logical Operators
PHP
1234567$x = true;
$y = false;
$x && $y; // And
$x || $y; // Or
!$x; // Not
$x xor $y; // Exclusive Or
Control Structures
Conditional Statements
PHP
123456789101112131415161718192021// If-Else
if ($condition) {
// Code
} elseif ($another_condition) {
// Code
} else {
// Code
}
// Ternary Operator
$result = $condition ? $value_if_true : $value_if_false;
// Short Ternary (Elvis)
$value = $input ?: 'default';
// Null Coalescing Operator
$username = $_GET['user'] ?? 'Guest';
// Null Coalescing Assignment
$config['timeout'] ??= 30;
Loops
PHP
1234567891011121314151617181920212223242526272829// For Loop
for ($i = 0; $i < 10; $i++) {
// Code
}
// While Loop
while ($condition) {
// Code
}
// Do-While Loop
do {
// Code
} while ($condition);
// Foreach (array iteration)
$array = [1, 2, 3];
foreach ($array as $value) {
// Code
}
foreach ($assoc_array as $key => $value) {
// Code
}
// Loop Control
break; // Exit loop
continue; // Skip current iteration
Functions
PHP
123456789101112131415161718192021222324252627282930313233// Basic Function
function greet($name) {
return "Hello, $name!";
}
// Function with Type Hints and return type
function addNumbers(int $a, int $b): int {
return $a + $b;
}
// Union and nullable types (PHP 8.0+)
function findUser(int|string $id): ?User {
// ...
}
// Anonymous Functions (Closures)
$multiply = function($a, $b) {
return $a * $b;
};
// Arrow Functions (PHP 7.4+) — implicit return, auto-captures by value
$numbers = [1, 2, 3, 4];
$squared = array_map(fn($n) => $n ** 2, $numbers);
// Variable-length Arguments
function sum(int ...$numbers): int {
return array_sum($numbers);
}
// First-class callable syntax (PHP 8.1+)
$strlen = strlen(...);
$method = $object->method(...);
Object-Oriented Programming
Classes and Objects
PHP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051class Person {
// Constructor property promotion (PHP 8.0+)
public function __construct(
public readonly string $name,
private int $age,
) {}
// Method
public function introduce(): string {
return "I'm {$this->name}, {$this->age} years old.";
}
}
// Object Creation
$person = new Person("John", 30);
echo $person->introduce();
// New in initializers (PHP 8.1+)
class Service {
public function __construct(
private Logger $logger = new NullLogger(),
) {}
}
// Inheritance
class Student extends Person {
public function __construct(
string $name,
int $age,
public string $school,
) {
parent::__construct($name, $age);
}
}
// Interfaces
interface Printable {
public function print(): void;
}
// Traits
trait Loggable {
public function log(string $message): void {
echo $message;
}
}
// Readonly classes (PHP 8.2+) — all properties are readonly
readonly class Point {
public function __construct(
public float $x,
public float $y,
) {}
}
// Abstract classes
abstract class Shape {
abstract public function area(): float;
}
// Final classes / methods
final class ImmutableConfig { /* ... */ }
Enums (PHP 8.1+)
PHP
12345678910111213141516171819202122232425// Pure enum
enum Status {
case Active;
case Inactive;
case Pending;
}
// Backed enum
enum HttpStatus: int {
case OK = 200;
case NotFound = 404;
case ServerError = 500;
public function label(): string {
return match($this) {
self::OK => 'OK',
self::NotFound => 'Not Found',
self::ServerError => 'Server Error',
};
}
}
$status = HttpStatus::from(200);
$maybe = HttpStatus::tryFrom(999); // null on invalid value
Error Handling
PHP
123456789101112131415161718192021// Try-Catch
try {
if ($error_condition) {
throw new RuntimeException("An error occurred");
}
} catch (RuntimeException | LogicException $e) {
// Multi-catch (PHP 8.0+ supports omitting the variable)
echo $e->getMessage();
} catch (Throwable $e) {
// Catches both Exception and Error
error_log($e);
} finally {
// Optional cleanup code
}
// Custom Error Handling
set_error_handler(function(int $errno, string $errstr): bool {
// Custom error logic
return true;
});
File I/O
PHP
123456789101112// Reading Files
$content = file_get_contents('file.txt');
$lines = file('file.txt');
// Writing Files
file_put_contents('output.txt', 'Hello, World!');
// File System Operations
is_file('file.txt');
mkdir('new_directory', 0755, recursive: true);
unlink('file.txt'); // Delete file
Database Connectivity (PDO)
PHP
1234567891011121314151617181920try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb;charset=utf8mb4',
'username',
'password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
// Always use prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE status = :status');
$stmt->execute(['status' => 'active']);
$users = $stmt->fetchAll();
} catch (PDOException $e) {
error_log("Connection failed: " . $e->getMessage());
}
Web Development Features
PHP
12345678910111213141516171819202122232425// Form Handling — always validate and sanitize
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS) ?? '';
$password = $_POST['password'] ?? '';
// Session Management
session_start([
'cookie_secure' => true,
'cookie_httponly' => true,
'cookie_samesite' => 'Lax',
]);
$_SESSION['user_id'] = $user->id;
// Cookies
setcookie('username', 'john_doe', [
'expires' => time() + 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
// URL Redirection
header('Location: welcome.php');
exit();
Namespaces and Autoloading
PHP
1234567891011121314151617// Namespace Declaration
namespace MyApp\Models;
// Grouped use declarations
use MyApp\{Models\User, Services\Auth, Utils\Logger};
// Autoloading with Composer (PSR-4)
// In composer.json:
// {
// "autoload": {
// "psr-4": {
// "MyApp\\": "src/"
// }
// }
// }
// Run: composer dump-autoload
Testing with PHPUnit
PHP
123456789101112131415161718192021222324use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\DataProvider;
final class UserTest extends TestCase {
#[Test]
public function userCanBeCreated(): void {
$user = new User('john', 'password');
$this->assertInstanceOf(User::class, $user);
}
#[DataProvider('emailProvider')]
public function testEmailValidation(string $email, bool $expected): void {
$this->assertSame($expected, User::isValidEmail($email));
}
public static function emailProvider(): array {
return [
['valid@example.com', true],
['invalid', false],
];
}
}
Modern PHP Features (PHP 8.x)
PHP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051// Named Arguments
function createUser(string $name, int $age, bool $admin = false) { }
createUser(name: 'John', age: 30, admin: true);
// Attributes
#[Route('/api/posts', methods: ['GET'])]
class PostController { }
// Match Expression (strict comparison, exhaustive)
$result = match($status) {
200, 201, 204 => 'Success',
404 => 'Not Found',
500, 502, 503 => 'Server Error',
default => 'Unknown',
};
// Nullsafe Operator
$country = $user?->getAddress()?->getCountry();
// Readonly properties (PHP 8.1+)
class DTO {
public function __construct(
public readonly string $id,
) {}
}
// Readonly classes (PHP 8.2+)
readonly class ValueObject {
public function __construct(public string $value) {}
}
// Disjunctive Normal Form (DNF) types (PHP 8.2+)
function process((Countable&Traversable)|null $items): void { }
// Asymmetric visibility (PHP 8.4+) — public read, private write
class Account {
public private(set) int $balance = 0;
}
// Property hooks (PHP 8.4+)
class User {
public string $fullName {
get => "{$this->first} {$this->last}";
set (string $value) {
[$this->first, $this->last] = explode(' ', $value, 2);
}
}
public function __construct(
private string $first,
private string $last,
) {}
}
// New without parentheses for method chaining (PHP 8.4+)
$result = new Service()->process()->getResult();
Security Considerations
- Always validate and sanitize user input (
filter_input,htmlspecialchars) - Use prepared statements with bound parameters for all database queries
- Implement CSRF protection on state-changing requests
- Use
password_hash()/password_verify()(Argon2id is the default since PHP 7.4) - Set
Secure,HttpOnly, andSameSitecookie flags - Enable HTTPS everywhere and use HSTS
- Keep PHP and dependencies updated; run
composer auditregularly - Disable
expose_phpanddisplay_errorsin production - Use Content Security Policy (CSP) headers
Best Practices
- Use Composer for dependency management
- Follow PSR coding standards (PSR-1, PSR-4, PSR-12)
- Declare
strict_types=1at the top of every file - Use type hints, return types, and property types everywhere
- Prefer readonly properties / classes for immutable value objects
- Leverage enums instead of class constants for fixed sets of values
- Use static analysis tools (PHPStan, Psalm) at the highest level you can sustain
- Format code with PHP-CS-Fixer or PHP_CodeSniffer
- Implement proper error logging via PSR-3 (Monolog)
Resources for Further Learning
- Official PHP Documentation: https://www.php.net/docs
- PHP-FIG (Framework Interop Group): https://www.php-fig.org/
- Composer: https://getcomposer.org/
- PHPUnit: https://phpunit.de/
- PHPStan: https://phpstan.org/
- Psalm: https://psalm.dev/
- Laravel Framework: https://laravel.com/
- Symfony Framework: https://symfony.com/
Performance and Optimization Tips
- Use the latest stable PHP version (8.4) for best performance
- Enable OPcache for bytecode caching in production
- Enable the JIT compiler (
opcache.jit=tracing) for CPU-bound workloads - Use preloading (
opcache.preload) to warm classes at server start - Minimize database queries; avoid N+1 patterns
- Cache expensive computations (APCu, Redis, Memcached)
- Profile your code with Xdebug, Blackfire, or Tideways
- Consider FrankenPHP, RoadRunner, or Swoole for long-running worker processes
Package Management with Composer
Bash
123456789101112131415161718# Install a dev dependency
composer require --dev phpunit/phpunit
# Create new project
composer create-project symfony/skeleton my-project
# Add runtime dependency
composer require symfony/http-client
# Update dependencies respecting constraints
composer update
# Audit installed packages for known vulnerabilities
composer audit
# Regenerate optimized autoloader for production
composer dump-autoload --optimize --classmap-authoritative
Continue Learning
Discover more cheatsheets to boost your productivity