What is PHP?
PHP is a popular general-purpose scripting language especially suited to web development. Fast, flexible, and pragmatic, PHP powers everything from blogs to the world's largest websites.
Server-Side Scripting
Runs on the server, generates HTML dynamically. Powers WordPress, Laravel, Symfony, and millions of sites.
Easy to Learn
Simple syntax, forgiving nature, and immediate results. Perfect for beginners and productive for experts.
Modern & Evolving
PHP 8+ brings JIT compilation, union types, attributes, enums, and performance improvements.
Rich Ecosystem
Composer for packages, massive standard library, frameworks like Laravel, Symfony, and vibrant community.
Basics
Hello World
<?php echo "Hello, World!"; // Short echo tag (requires short_open_tag enabled) <?= "Hello, World!" ?>
Variables
<?php // Variables start with $ $name = "Alice"; $age = 30; $price = 19.99; $isActive = true; // Variable variables $var = "name"; echo $$var; // prints "Alice" // Constants const MAX_SIZE = 100; define("API_KEY", "secret"); // Interpolation (double quotes only) echo "Hello, $name!"; echo "Hello, {$name}!"; // clearer syntax
Data Types
// Scalar types $str = "string"; // string $int = 42; // int $float = 3.14; // float $bool = true; // bool // Compound types $array = [1, 2, 3]; // array $obj = new stdClass(); // object $callback = fn() => 1; // callable // Special types $null = null; // null $resource = fopen("file.txt", "r"); // resource // Type checking is_string($str); is_int($int); is_array($array); gettype($var);
Control Flow
// if/else if ($age >= 18) { echo "Adult"; } elseif ($age >= 13) { echo "Teen"; } else { echo "Child"; } // Ternary $status = $age >= 18 ? "adult" : "minor"; // Null coalescing $name = $_GET['name'] ?? "Guest"; // Null coalescing assignment (PHP 7.4+) $data['key'] ??= "default"; // switch switch ($role) { case "admin": echo "Full access"; break; case "user": echo "Limited access"; break; default: echo "No access"; } // Loops for ($i = 0; $i < 10; $i++) { echo $i; } while ($condition) { // do something } foreach ($array as $value) { echo $value; } foreach ($array as $key => $value) { echo "$key: $value"; }
Type Declarations
PHP 7+ introduced scalar type hints and return types. PHP 8+ added union types, mixed type, and more.
Function Types
// Parameter types function greet(string $name): void { echo "Hello, $name!"; } // Return type function add(int $a, int $b): int { return $a + $b; } // Nullable types function find(int $id): ?User { return $user ?? null; } // Union types (PHP 8.0+) function process(int|float $num): string|int { return $num * 2; } // Mixed type (any type) function anything(mixed $value): mixed { return $value; }
Property Types (PHP 7.4+)
class User { public string $name; public int $age; private ?string $email = null; public array $roles = []; // Readonly properties (PHP 8.1+) public readonly string $id; } // Readonly class (PHP 8.2+) readonly class Point { public function __construct( public float $x, public float $y, ) {} }
Strict Types
<?php // Enable strict typing (must be first line) declare(strict_types=1); function multiply(int $a, int $b): int { return $a * $b; } multiply(2, 3); // OK multiply("2", "3"); // TypeError in strict mode
Functions
Basic Functions
// Standard function function sayHello(string $name = "World"): string { return "Hello, $name!"; } // Variadic function function sum(int ...$numbers): int { return array_sum($numbers); } sum(1, 2, 3, 4); // 10 // Named arguments (PHP 8.0+) function createUser(string $name, int $age, string $email): array { return compact('name', 'age', 'email'); } createUser(age: 25, name: "Alice", email: "a@ex.com");
Anonymous Functions & Closures
// Anonymous function $greet = function(string $name): string { return "Hello, $name!"; }; echo $greet("Alice"); // Closure with use $multiplier = 3; $times = function(int $n) use ($multiplier): int { return $n * $multiplier; }; // Arrow functions (PHP 7.4+) $double = fn($n) => $n * 2; $add = fn($a, $b) => $a + $b; // Automatically captures parent scope $multiplier = 3; $times = fn($n) => $n * $multiplier; // no 'use' needed
First-Class Callables (PHP 8.1+)
// Create callable reference $strlen = strlen(...); $array_map = array_map(...); // Method references $count = ["hello", "world"]; $lengths = array_map(strlen(...), $count);
Object-Oriented Programming
Classes & Objects
class User { // Properties public string $name; private int $age; protected array $roles = []; // Constructor public function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } // Methods public function getAge(): int { return $this->age; } // Static method public static function create(string $name): self { return new self($name, 0); } } // Create instance $user = new User("Alice", 30); $user2 = User::create("Bob");
Constructor Property Promotion (PHP 8.0+)
// Before PHP 8 class Point { public float $x; public float $y; public function __construct(float $x, float $y) { $this->x = $x; $this->$y = $y; } } // PHP 8+ (much cleaner!) class Point { public function __construct( public float $x, public float $y, ) {} }
Inheritance
class Animal { public function __construct( protected string $name ) {} public function speak(): string { return "..."; } } class Dog extends Animal { public function speak(): string { return "Woof!"; } public function getName(): string { return $this->name; // access protected } }
Interfaces & Traits
// Interface interface Renderable { public function render(): string; } // Trait (code reuse) trait Timestampable { public DateTime $createdAt; public DateTime $updatedAt; public function touch(): void { $this->updatedAt = new DateTime(); } } class Post implements Renderable { use Timestampable; public function render(): string { return "<article>...</article>"; } }
Abstract Classes
abstract class Shape { abstract public function area(): float; public function describe(): string { return "Area: " . $this->area(); } } class Circle extends Shape { public function __construct( private float $radius ) {} public function area(): float { return M_PI * $this->$radius ** 2; } }
Modern PHP Features
Match Expression (PHP 8.0+)
// More strict than switch $result = match($status) { 200, 201 => "Success", 404 => "Not Found", 500 => "Server Error", default => "Unknown", }; // Returns value (no break needed) $message = match($age) { 0 => "newborn", 1, 2 => "toddler", 3, 4, 5 => "child", default => $age >= 18 ? "adult" : "minor", };
Enumerations (PHP 8.1+)
// Pure enum enum Status { case Pending; case Approved; case Rejected; } $status = Status::Pending; // Backed enum (with values) enum HttpStatus: int { case OK = 200; case NotFound = 404; case ServerError = 500; public function isError(): bool { return $this->value >= 400; } } echo HttpStatus::OK->value; // 200
Attributes (PHP 8.0+)
// Define attribute #[Attribute] class Route { public function __construct( public string $path, public string $method = 'GET', ) {} } // Use attribute class UserController { #[Route('/users', method: 'GET')] public function index(): array { return []; } #[Route('/users/{id}', method: 'GET')] public function show(int $id): array { return []; } }
Nullsafe Operator (PHP 8.0+)
// Old way $country = null; if ($user !== null) { if ($user->getAddress() !== null) { $country = $user->getAddress()->getCountry(); } } // Nullsafe operator $country = $user?->getAddress()?->getCountry();
Named Arguments (PHP 8.0+)
function createUser( string $name, string $email, int $age = 0, bool $active = true ): array { return compact('name', 'email', 'age', 'active'); } // Named arguments - order doesn't matter createUser( email: 'alice@example.com', name: 'Alice', active: false, );
Arrays
Array Basics
// Indexed array $fruits = ["apple", "banana", "cherry"]; $numbers = array(1, 2, 3); // old syntax // Associative array (dictionary/hash) $user = [ "name" => "Alice", "age" => 30, "email" => "alice@example.com", ]; // Access echo $fruits[0]; // "apple" echo $user["name"]; // "Alice" // Add elements $fruits[] = "date"; $user["city"] = "NYC"; // Check existence isset($user["email"]); array_key_exists("name", $user);
Array Functions
// Common operations count($array); // length array_push($arr, $item); // add to end array_pop($arr); // remove from end array_shift($arr); // remove from start array_unshift($arr, $item); // add to start // Transform $doubled = array_map(fn($n) => $n * 2, $numbers); $evens = array_filter($numbers, fn($n) => $n % 2 === 0); $sum = array_reduce($numbers, fn($acc, $n) => $acc + $n, 0); // Search & check in_array("apple", $fruits); array_search("apple", $fruits); // Sort sort($arr); // ascending rsort($arr); // descending asort($arr); // preserve keys usort($arr, fn($a, $b) => $a <=> $b); // custom // Merge & split $merged = array_merge($arr1, $arr2); $spread = [...$arr1, ...$arr2]; // spread operator $chunk = array_chunk($arr, 3); $slice = array_slice($arr, 1, 3);
Array Destructuring
// List destructuring [$first, $second] = ["a", "b"]; // Skip elements [$first, , $third] = [1, 2, 3]; // Associative array destructuring ['name' => $name, 'age' => $age] = $user; // In foreach foreach ($users as ['name' => $name, 'email' => $email]) { echo "$name: $email"; }
Error Handling
Exceptions
// Try-catch try { $result = riskyOperation(); } catch (InvalidArgumentException $e) { echo "Invalid argument: " . $e->getMessage(); } catch (RuntimeException $e) { echo "Runtime error: " . $e->getMessage(); } catch (Exception $e) { echo "Error: " . $e->getMessage(); } finally { // Always runs cleanup(); } // Multi-catch (PHP 7.1+) catch (InvalidArgumentException | RuntimeException $e) { handleError($e); }
Custom Exceptions
class UserNotFoundException extends Exception { public function __construct(int $userId) { parent::__construct("User $userId not found"); } } throw new UserNotFoundException(123);
Error Handling
// Set error handler set_error_handler(function($errno, $errstr, $errfile, $errline) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); }); // Error suppression (avoid if possible) $file = @file_get_contents('missing.txt');
Standard Library Highlights
String Functions
strlen($str); // length str_contains($str, 'word'); // PHP 8+ str_starts_with($str, 'pre'); // PHP 8+ str_ends_with($str, 'fix'); // PHP 8+ strtolower($str); strtoupper($str); trim($str); // remove whitespace explode(',', $str); // string to array implode(',', $arr); // array to string substr($str, 0, 5); // substring str_replace('old', 'new', $str); preg_match('/pattern/', $str); // regex
File I/O
// Read file $content = file_get_contents('file.txt'); $lines = file('file.txt'); // array of lines // Write file file_put_contents('file.txt', $content); // File operations file_exists('file.txt'); is_file('file.txt'); is_dir('path/to/dir'); unlink('file.txt'); // delete mkdir('dir'); rmdir('dir'); // Stream operations $handle = fopen('file.txt', 'r'); while (($line = fgets($handle)) !== false) { echo $line; } fclose($handle);
JSON
// Encode $json = json_encode($data); $pretty = json_encode($data, JSON_PRETTY_PRINT); // Decode $data = json_decode($json, true); // to array $obj = json_decode($json); // to object // Check errors if (json_last_error() !== JSON_ERROR_NONE) { echo json_last_error_msg(); }
Date & Time
// DateTime object $now = new DateTime(); $date = new DateTime('2025-12-31'); $date = DateTime::createFromFormat('Y-m-d', '2025-12-31'); // Format echo $date->format('Y-m-d H:i:s'); echo $date->format(DateTime::ISO8601); // Modify $date->modify('+1 day'); $date->add(new DateInterval('P1D')); // +1 day $date->sub(new DateInterval('P1M')); // -1 month // Compare $diff = $date1->diff($date2); echo $diff->days;
Composer & Package Management
Common Commands
# Initialize project composer init # Install dependencies composer install # Update dependencies composer update # Add package composer require vendor/package composer require --dev phpunit/phpunit # Remove package composer remove vendor/package # Autoload optimization composer dump-autoload -o # Run scripts composer run-script test
composer.json
{
"name": "vendor/project",
"description": "My project",
"type": "project",
"require": {
"php": "^8.2",
"vendor/package": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^10.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"scripts": {
"test": "phpunit",
"lint": "phpcs"
}
}
Autoloading
// Include Composer's autoloader require __DIR__ . '/vendor/autoload.php'; // Now use any installed packages use Vendor\Package\Class; use function Vendor\Package\helper; $instance = new Class(); helper();
Popular Packages
- laravel/framework
- Full-stack web framework with elegant syntax
- symfony/symfony
- Set of reusable PHP components and framework
- guzzlehttp/guzzle
- HTTP client for making API requests
- monolog/monolog
- Powerful logging library
- phpunit/phpunit
- Testing framework
- vlucas/phpdotenv
- Load environment variables from .env files