Built for developers, by XinhND

v2.1.0

Ready

PHP Cheat Sheet

Complete reference guide for PHP with interactive examples and live playground links

Basic Syntax

Hello World

Different ways to output text in PHP

PHP
<?php
// Basic output
echo "Hello, World!";
print "Hello, World!";

// HTML output
echo "<h1>Hello, World!</h1>";

// String concatenation
$name = "PHP";
echo "Hello, " . $name . "!";

// String interpolation
echo "Hello, $name!";
echo "Hello, {$name}!";
?>

Variables and Data Types

Variable declaration and basic data types in PHP

PHP
<?php
// Variable declaration
$name = "PHP";
$age = 30;
$isActive = true;

// Data types
$string = "Hello";        // String
$integer = 42;            // Integer
$float = 3.14;           // Float
$boolean = true;          // Boolean
$null = null;            // Null
$array = [1, 2, 3];      // Array
$object = new stdClass(); // Object

// Type checking
var_dump($string);       // string(5) "Hello"
is_string($string);      // true
is_int($integer);        // true
is_bool($boolean);       // true

// Type casting
$number = (int) "42";
$string = (string) 42;
$boolean = (bool) 1;

String Operations

Common string operations and formatting

PHP
<?php
$text = "Hello World";

// String functions
echo strtoupper($text);      // HELLO WORLD
echo strtolower($text);      // hello world
echo str_replace("World", "PHP", $text);  // Hello PHP
print_r(explode(" ", $text));  // ["Hello", "World"]
echo strlen($text);          // 11

// String formatting
$name = "Alice";
$age = 25;
printf("My name is %s and I'm %d years old", $name, $age);

// Heredoc syntax
$html = <<<HTML
    <div>
        <h1>$name</h1>
        <p>Age: $age</p>
    </div>
HTML;

Arrays

Working with arrays in PHP

PHP
<?php
// Indexed arrays
$fruits = ["apple", "banana", "cherry"];
array_push($fruits, "orange");
array_unshift($fruits, "grape");
array_pop($fruits);
array_shift($fruits);
echo $fruits[0];      // apple
echo count($fruits);  // 3

// Associative arrays
$person = [
    "name" => "Alice",
    "age" => 25,
    "job" => "Developer"
];
echo $person["name"];  // Alice

// Array functions
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers);
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
$sum = array_reduce($numbers, fn($a, $b) => $a + $b, 0);

// Array destructuring
[$first, $second, ...$rest] = $numbers;

Control Structures

Control flow statements in PHP

PHP
<?php
// If-else
if ($age >= 18) {
    echo "Adult";
} elseif ($age >= 13) {
    echo "Teenager";
} else {
    echo "Child";
}

// Switch
switch ($status) {
    case "active":
        echo "User is active";
        break;
    case "inactive":
        echo "User is inactive";
        break;
    default:
        echo "Unknown status";
}

// Loops
for ($i = 0; $i < 5; $i++) {
    echo $i;
}

foreach ($items as $item) {
    echo $item;
}

while ($condition) {
    // Do something
}

// Match expression (PHP 8.0+)
$result = match($status) {
    "active" => "User is active",
    "inactive" => "User is inactive",
    default => "Unknown status"
};

Functions

Function Definition

Different ways to define functions

PHP
<?php
// Basic function
function greet($name) {
    return "Hello, $name!";
}

// Function with type hints
function calculate(int $a, int $b): int {
    return $a + $b;
}

// Function with default parameters
function createUser($name, $age = 20) {
    return ["name" => $name, "age" => $age];
}

// Variadic functions
function sum(...$numbers) {
    return array_sum($numbers);
}

// Arrow functions (PHP 7.4+)
$multiply = fn($a, $b) => $a * $b;

// Callback functions
function processUser($name, callable $callback) {
    $user = ["name" => $name, "id" => time()];
    return $callback($user);
}

Anonymous Functions

Working with anonymous functions and closures

PHP
<?php
// Basic anonymous function
$greet = function($name) {
    return "Hello, $name!";
};

// Using anonymous function
$result = $greet("Alice");

// Using with array_map
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(function($n) {
    return $n * 2;
}, $numbers);

// Using with array_filter
$even = array_filter($numbers, function($n) {
    return $n % 2 === 0;
});

// Arrow function (PHP 7.4+)
$multiply = fn($a, $b) => $a * $b;

Object-Oriented Programming

Classes and Objects

Basic class and object usage

PHP
<?php
// Class definition
class User {
    // Properties
    private string $name;
    private int $age;
    
    // Constructor
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
    
    // Methods
    public function getName(): string {
        return $this->name;
    }
    
    public function getAge(): int {
        return $this->age;
    }
    
    public function greet(): string {
        return "Hello, I'm {$this->name}";
    }
}

// Creating objects
$user = new User("Alice", 25);
echo $user->getName();  // Alice
echo $user->greet();    // Hello, I'm Alice

Inheritance and Interfaces

Inheritance, interfaces, and abstract classes

PHP
<?php
// Interface
interface Logger {
    public function log(string $message): void;
}

// Abstract class
abstract class BaseLogger implements Logger {
    protected string $prefix;
    
    public function __construct(string $prefix) {
        $this->prefix = $prefix;
    }
    
    abstract protected function format(string $message): string;
}

// Concrete class
class FileLogger extends BaseLogger {
    protected function format(string $message): string {
        return "[{$this->prefix}] $message";
    }
    
    public function log(string $message): void {
        $formatted = $this->format($message);
        file_put_contents("log.txt", $formatted . PHP_EOL, FILE_APPEND);
    }
}

// Using the classes
$logger = new FileLogger("INFO");
$logger->log("User logged in");

Traits

Using traits for code reuse

PHP
<?php
// Trait definition
trait Timestampable {
    private DateTime $createdAt;
    
    public function setCreatedAt(DateTime $date): void {
        $this->createdAt = $date;
    }
    
    public function getCreatedAt(): DateTime {
        return $this->createdAt;
    }
}

// Using trait
class Post {
    use Timestampable;
    
    private string $title;
    
    public function __construct(string $title) {
        $this->title = $title;
        $this->setCreatedAt(new DateTime());
    }
}

// Using the class
$post = new Post("Hello World");
echo $post->getCreatedAt()->format("Y-m-d H:i:s");

Modern Features

Null Safe Operator

Using the null safe operator

PHP
<?php
// Null safe operator (PHP 8.0+)
$user = null;
$name = $user?->getName() ?? "Guest";

// Traditional way
$name = $user !== null ? $user->getName() : "Guest";

// Chaining
$country = $user?->getAddress()?->getCountry() ?? "Unknown";

// With arrays
$firstItem = $array?[0] ?? "default";

Named Arguments

Using named arguments in PHP 8.0+

PHP
<?php
// Function with named arguments
function createUser(
    string $name,
    int $age = 20,
    string $role = "user"
) {
    return [
        "name" => $name,
        "age" => $age,
        "role" => $role
    ];
}

// Using named arguments
$user = createUser(
    name: "Alice",
    role: "admin"
);

// Traditional way
$user = createUser("Alice", 20, "admin");

Attributes

Using attributes in PHP 8.0+

PHP
<?php
// Attribute definition
#[Attribute]
class Route {
    public function __construct(
        public string $path,
        public string $method = "GET"
    ) {}
}

// Using attributes
#[Route("/users", "GET")]
class UserController {
    #[Route("/users/{id}", "GET")]
    public function show(int $id) {
        // ...
    }
}

// Reading attributes
$reflection = new ReflectionClass(UserController::class);
$attributes = $reflection->getAttributes(Route::class);

Database Operations

PDO Connection

Basic database operations with PDO

PHP
<?php
// Database connection
try {
    $pdo = new PDO(
        "mysql:host=localhost;dbname=mydb",
        "username",
        "password",
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch();

// Named parameters
$stmt = $pdo->prepare("SELECT * FROM users WHERE name = :name");
$stmt->execute(["name" => $name]);
$user = $stmt->fetch();

Transactions

Working with database transactions

PHP
<?php
try {
    $pdo->beginTransaction();
    
    // Multiple operations
    $stmt1 = $pdo->prepare("INSERT INTO users (name) VALUES (?)");
    $stmt1->execute([$name]);
    
    $userId = $pdo->lastInsertId();
    
    $stmt2 = $pdo->prepare("INSERT INTO profiles (user_id) VALUES (?)");
    $stmt2->execute([$userId]);
    
    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    throw $e;
}

PHP - Interactive Developer Reference

Hover over code blocks to copy or run in live playground