LearnThatStack Ace your next interview

PHP.
Cheatsheet.

Quick reference for PHP - sectioned for fast scanning. Skim the part you're shaky on, walk in confident.

Backend Development 26-section reference ~13 min read

Overview

PHP Backend Development Interview Cheat Sheet

Introduction

Comprehensive PHP reference for technical interviews covering PHP 8+ features, OOP, database operations, security, design patterns, and modern development practices. Master these concepts to excel in backend PHP positions.

Key Areas: Core syntax • OOP & SOLID • Database/PDO • Security • Performance • Testing • Modern PHP 8+ features

1. PHP Basics

PHP Tags & Output

<?php echo "Hello"; ?>           // Standard tags
<?= "Hello" ?>                   // Short echo tag
print "Hello";                   // Alternative output

Comments

// Single line comment
# Alternative single line
/* Multi-line 
   comment */
/** 
 * PHPDoc comment
 */

Constants

define('DB_NAME', 'mydb');       // Global constant
const MAX_SIZE = 100;            // Class constant
defined('DB_NAME');              // Check if defined

2. Data Types & Variables

Scalar Types

$string = "Hello";               // String
$integer = 42;                   // Integer
$float = 3.14;                   // Float/Double
$boolean = true;                 // Boolean

Compound Types

$array = [1, 2, 3];             // Array
$object = new stdClass();        // Object
$callable = 'functionName';      // Callable
$iterable = [1, 2, 3];          // Iterable (PHP 7.1+)

Special Types

$null = null;                    // NULL
$resource = fopen('file.txt', 'r'); // Resource

Type Checking

is_string($var);    is_int($var);     is_float($var);
is_bool($var);      is_array($var);   is_object($var);
is_null($var);      is_numeric($var); is_callable($var);
gettype($var);      // Returns type as string

Type Casting

(string) $var;      (int) $var;       (float) $var;
(bool) $var;        (array) $var;     (object) $var;

3. Operators

Comparison Operators

==   // Equal (type coercion)
===  // Identical (strict)
!=   // Not equal
!==  // Not identical
<=>  // Spaceship operator (PHP 7+)
??   // Null coalescing (PHP 7+)
?:   // Ternary shorthand

Example:

$a = 5 <=> 3;        // Returns 1 (5 > 3)
$b = $x ?? 'default'; // Use $x if set, else 'default'
$c = $x ?: 'default'; // Use $x if truthy, else 'default'

4. Control Structures

Conditionals

if ($condition) {
    // code
} elseif ($other) {
    // code
} else {
    // code
}

// Switch
switch ($var) {
    case 'value1':
        // code
        break;
    case 'value2':
        // code
        break;
    default:
        // code
}

// Match expression (PHP 8+)
$result = match($value) {
    1 => 'one',
    2 => 'two',
    default => 'other'
};

Loops

// For loop
for ($i = 0; $i < 10; $i++) { }

// While loop
while ($condition) { }

// Do-while
do { } while ($condition);

// Foreach
foreach ($array as $value) { }
foreach ($array as $key => $value) { }

5. Functions

Function Declaration

function greet($name, $greeting = "Hello") {
    return "$greeting, $name!";
}

// Type declarations (PHP 7+)
function add(int $a, int $b): int {
    return $a + $b;
}

// Nullable types (PHP 7.1+)
function process(?string $data): ?array {
    return $data ? explode(',', $data) : null;
}

// Union types (PHP 8+)
function getId(): int|string {
    return $_GET['id'] ?? 'default';
}

Anonymous Functions & Closures

$greet = function($name) {
    return "Hello, $name";
};

// With use keyword
$message = 'Hello';
$greet = function($name) use ($message) {
    return "$message, $name";
};

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

Variable Functions

$func = 'strlen';
$length = $func('Hello');  // Calls strlen()

6. Arrays

Array Creation

$indexed = [1, 2, 3];
$assoc = ['name' => 'John', 'age' => 30];
$multi = [
    ['a', 'b'],
    ['c', 'd']
];

Array Functions

// Adding/Removing
array_push($arr, $val);          // Add to end
array_pop($arr);                 // Remove from end
array_unshift($arr, $val);       // Add to beginning
array_shift($arr);               // Remove from beginning

// Searching
in_array($needle, $haystack);    // Check if exists
array_search($needle, $haystack); // Get key
array_key_exists($key, $arr);    // Check key

// Transforming
array_map($callback, $arr);      // Apply function
array_filter($arr, $callback);   // Filter elements
array_reduce($arr, $callback);   // Reduce to single value

// Sorting
sort($arr);         // Sort by value
rsort($arr);        // Reverse sort
asort($arr);        // Sort preserving keys
ksort($arr);        // Sort by keys
usort($arr, $callback); // Custom sort

// Other useful
array_merge($arr1, $arr2);       // Merge arrays
array_combine($keys, $values);   // Create from keys/values
array_slice($arr, $offset, $length); // Extract portion
array_unique($arr);              // Remove duplicates
array_values($arr);              // Re-index
array_keys($arr);                // Get all keys

Array Destructuring (PHP 7.1+)

[$a, $b, $c] = [1, 2, 3];
['name' => $name, 'age' => $age] = $user;

7. Object-Oriented Programming

Classes & Objects

class User {
    // Properties
    public string $name;
    private int $age;
    protected string $email;
    
    // 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(array $data): self {
        return new self($data['name'], $data['age']);
    }
}

$user = new User('John', 30);

Inheritance

class Admin extends User {
    private array $permissions;
    
    public function __construct(string $name, int $age, array $perms) {
        parent::__construct($name, $age);
        $this->permissions = $perms;
    }
}

Interfaces

interface PaymentInterface {
    public function process(float $amount): bool;
    public function refund(string $transactionId): bool;
}

class CreditCard implements PaymentInterface {
    public function process(float $amount): bool {
        // Implementation
        return true;
    }
    
    public function refund(string $transactionId): bool {
        // Implementation
        return true;
    }
}

Abstract Classes

abstract class Vehicle {
    protected string $brand;
    
    abstract public function start(): void;
    
    public function getBrand(): string {
        return $this->brand;
    }
}

class Car extends Vehicle {
    public function start(): void {
        echo "Car started";
    }
}

Traits

trait Timestampable {
    protected DateTime $createdAt;
    protected DateTime $updatedAt;
    
    public function touch(): void {
        $this->updatedAt = new DateTime();
    }
}

class Post {
    use Timestampable;
}

Magic Methods

__construct()    // Constructor
__destruct()     // Destructor
__get($name)     // Called when accessing inaccessible property
__set($name, $value) // Called when setting inaccessible property
__isset($name)   // Called when using isset() on inaccessible property
__unset($name)   // Called when using unset() on inaccessible property
__call($name, $args) // Called when calling inaccessible method
__toString()     // Called when object is treated as string
__invoke()       // Called when object is used as function
__clone()        // Called when object is cloned

Visibility Modifiers

  • public: Accessible everywhere
  • private: Accessible only within the class
  • protected: Accessible within class and subclasses

8. Namespaces & Autoloading

Namespaces

namespace App\Models;

use App\Contracts\UserInterface;
use DateTime;

class User implements UserInterface {
    // Class definition
}

Autoloading (PSR-4)

// composer.json
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

// Usage
require 'vendor/autoload.php';
use App\Models\User;

9. Error Handling

Exceptions

try {
    if (!$valid) {
        throw new Exception('Invalid data');
    }
} catch (Exception $e) {
    echo $e->getMessage();
    echo $e->getCode();
    echo $e->getFile();
    echo $e->getLine();
} finally {
    // Always executed
}

Custom Exceptions

class ValidationException extends Exception {
    protected array $errors;
    
    public function __construct(array $errors) {
        $this->errors = $errors;
        parent::__construct('Validation failed');
    }
    
    public function getErrors(): array {
        return $this->errors;
    }
}

Error Reporting

error_reporting(E_ALL);  // Report all errors
ini_set('display_errors', 1); // Display errors (dev only)
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    // Custom error handler
});

10. Database Operations (PDO)

Connection

try {
    $pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

Prepared Statements

// Insert
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->execute(['name' => 'John', 'email' => 'john@example.com']);

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

// Fetch all
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

Transactions

try {
    $pdo->beginTransaction();
    
    $pdo->exec("INSERT INTO users VALUES (...)");
    $pdo->exec("UPDATE accounts SET ...");
    
    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    throw $e;
}

11. Sessions & Cookies

Sessions

session_start();                 // Start session
$_SESSION['user_id'] = 123;     // Set session data
$userId = $_SESSION['user_id']; // Get session data
unset($_SESSION['user_id']);    // Remove specific data
session_destroy();               // Destroy entire session
session_regenerate_id(true);     // Regenerate session ID

Cookies

// Set cookie
setcookie('name', 'value', time() + 3600, '/', '', true, true);
// Parameters: name, value, expire, path, domain, secure, httponly

// Get cookie
$value = $_COOKIE['name'] ?? null;

// Delete cookie
setcookie('name', '', time() - 3600);

12. Security Best Practices

Input Validation & Sanitization

// Filter input
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);

// Sanitize output
$html = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
$url = urlencode($userInput);

Password Hashing

// Hash password
$hash = password_hash($password, PASSWORD_DEFAULT);

// Verify password
if (password_verify($password, $hash)) {
    // Password is correct
}

// Check if rehash needed
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
    $newHash = password_hash($password, PASSWORD_DEFAULT);
}

CSRF Protection

// Generate token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// Verify token
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    die('CSRF token validation failed');
}

SQL Injection Prevention

// Always use prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);

// Never do this:
$query = "SELECT * FROM users WHERE email = '$email'"; // UNSAFE!

13. File Handling

File Operations

// Read file
$content = file_get_contents('file.txt');
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);

// Write file
file_put_contents('file.txt', $content);
file_put_contents('file.txt', $content, FILE_APPEND);

// File info
file_exists($filename);
is_file($filename);
is_dir($dirname);
filesize($filename);
filemtime($filename);  // Last modified time

File Upload

if ($_FILES['upload']['error'] === UPLOAD_ERR_OK) {
    $tmpName = $_FILES['upload']['tmp_name'];
    $name = basename($_FILES['upload']['name']);
    
    // Validate file type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $tmpName);
    
    if (in_array($mimeType, ['image/jpeg', 'image/png'])) {
        move_uploaded_file($tmpName, "uploads/$name");
    }
}

14. Design Patterns

Singleton

class Database {
    private static ?Database $instance = null;
    
    private function __construct() {}
    
    public static function getInstance(): Database {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

Factory

interface Logger {
    public function log(string $message): void;
}

class LoggerFactory {
    public static function create(string $type): Logger {
        return match($type) {
            'file' => new FileLogger(),
            'db' => new DatabaseLogger(),
            default => throw new Exception("Unknown logger type")
        };
    }
}

Dependency Injection

class UserService {
    private UserRepository $repository;
    
    public function __construct(UserRepository $repository) {
        $this->repository = $repository;
    }
    
    public function getUser(int $id): ?User {
        return $this->repository->find($id);
    }
}

Repository Pattern

interface UserRepository {
    public function find(int $id): ?User;
    public function findAll(): array;
    public function save(User $user): void;
    public function delete(int $id): void;
}

class MysqlUserRepository implements UserRepository {
    private PDO $pdo;
    
    public function find(int $id): ?User {
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetchObject(User::class) ?: null;
    }
    
    // Other methods...
}

15. Modern PHP Features

Attributes (PHP 8+)

#[Route('/users/{id}', methods: ['GET'])]
class UserController {
    #[Inject]
    private UserService $service;
    
    #[Deprecated('Use getUser() instead')]
    public function show(int $id) {}
}

Enums (PHP 8.1+)

enum Status: string {
    case PENDING = 'pending';
    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
    
    public function label(): string {
        return match($this) {
            self::PENDING => 'Pending Approval',
            self::ACTIVE => 'Active',
            self::INACTIVE => 'Inactive'
        };
    }
}

Named Arguments (PHP 8+)

function createUser(string $name, ?string $email = null, int $age = 18) {}

createUser(name: 'John', age: 25);  // Skip email parameter

Constructor Property Promotion (PHP 8+)

class User {
    public function __construct(
        private string $name,
        private int $age,
        public ?string $email = null
    ) {}
}

Readonly Properties (PHP 8.1+)

class User {
    public readonly string $id;
    
    public function __construct() {
        $this->id = uniqid();  // Can only be set once
    }
}

16. Performance Optimization

Caching

// APCu cache
if (apcu_exists('key')) {
    $data = apcu_fetch('key');
} else {
    $data = expensive_operation();
    apcu_store('key', $data, 3600);  // Cache for 1 hour
}

// File cache
$cacheFile = 'cache/data.json';
if (file_exists($cacheFile) && time() - filemtime($cacheFile) < 3600) {
    $data = json_decode(file_get_contents($cacheFile), true);
} else {
    $data = expensive_operation();
    file_put_contents($cacheFile, json_encode($data));
}

Opcode Caching

// Enable OPcache in php.ini
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000

Query Optimization

// Use indexes
$pdo->exec("CREATE INDEX idx_email ON users(email)");

// Limit results
$stmt = $pdo->prepare("SELECT * FROM users LIMIT 10 OFFSET ?");

// Use JOIN instead of multiple queries
$stmt = $pdo->prepare("
    SELECT u.*, p.* 
    FROM users u 
    JOIN posts p ON u.id = p.user_id 
    WHERE u.id = ?
");

17. Testing

Unit Testing with PHPUnit

use PHPUnit\Framework\TestCase;

class UserTest extends TestCase {
    public function testCanCreateUser(): void {
        $user = new User('John', 30);
        
        $this->assertEquals('John', $user->getName());
        $this->assertEquals(30, $user->getAge());
    }
    
    public function testEmailValidation(): void {
        $this->expectException(InvalidArgumentException::class);
        
        $user = new User('John', 30);
        $user->setEmail('invalid-email');
    }
}

Mocking

public function testUserService(): void {
    $mockRepo = $this->createMock(UserRepository::class);
    $mockRepo->expects($this->once())
             ->method('find')
             ->with(1)
             ->willReturn(new User('John', 30));
    
    $service = new UserService($mockRepo);
    $user = $service->getUser(1);
    
    $this->assertInstanceOf(User::class, $user);
}

18. Critical PHP Concepts

Comparison Operators Deep Dive

// == vs === (Type coercion vs Strict comparison)
1 == "1"   // true (coerces string to int)
1 === "1"  // false (different types)
0 == false // true
0 === false // false
null == undefined // true in loose comparison

Include vs Require

include 'file.php';      // Warning if not found, continues
require 'file.php';      // Fatal error if not found, stops
include_once 'file.php'; // Include only once (prevents duplicates)
require_once 'file.php'; // Require only once (most common)

HTTP Methods & Superglobals

// GET: Idempotent, cacheable, ~2KB limit, data in URL
$id = $_GET['id'] ?? null;

// POST: Non-idempotent, not cacheable, no limit, data in body  
$data = $_POST['data'] ?? null;

// Superglobals (always accessible)
$_GET, $_POST, $_SESSION, $_COOKIE, $_FILES
$_SERVER, $_ENV, $GLOBALS, $_REQUEST

Late Static Binding

class A {
    public static function who() { echo __CLASS__; }
    public static function test() { 
        self::who();   // Always calls A::who()
        static::who(); // Calls actual class (late binding)
    }
}
class B extends A {
    public static function who() { echo __CLASS__; }
}
B::test(); // self outputs: A, static outputs: B

Generators (Memory Efficient Iteration)

// Memory: O(1) instead of O(n)
function getRange($max) {
    for ($i = 0; $i < $max; $i++) {
        yield $i;  // Pause and return value
    }
}

foreach (getRange(1000000) as $num) {
    // Process one at a time, minimal memory
}

CORS Headers

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: https://example.com');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    header('Access-Control-Max-Age: 86400'); // Cache preflight
    exit(0);
}

## 19. Composer & Dependency Management

### Essential Commands
```bash
composer init                    # Initialize project
composer require vendor/package  # Add dependency
composer install                 # Install from composer.lock
composer update                  # Update dependencies
composer dump-autoload -o        # Optimize autoloader
composer show                    # List installed packages

composer.json Structure

{
    "require": {
        "php": ">=8.1",
        "monolog/monolog": "^3.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^10.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "scripts": {
        "test": "phpunit",
        "format": "php-cs-fixer fix"
    }
}

20. REST API Development

RESTful Routing

// REST endpoints follow conventions
GET    /users          // List all users
GET    /users/{id}     // Get specific user
POST   /users          // Create new user
PUT    /users/{id}     // Update entire user
PATCH  /users/{id}     // Partial update
DELETE /users/{id}     // Delete user

API Response Structure

class ApiResponse {
    public static function success($data, $code = 200) {
        http_response_code($code);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'data' => $data
        ]);
    }
    
    public static function error($message, $code = 400) {
        http_response_code($code);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'error' => $message
        ]);
    }
}

JWT Authentication

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// Generate token
$payload = [
    'user_id' => $userId,
    'exp' => time() + 3600  // 1 hour expiry
];
$jwt = JWT::encode($payload, $secretKey, 'HS256');

// Verify token
try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $userId = $decoded->user_id;
} catch (Exception $e) {
    // Invalid token
}

21. Performance & Complexity

Array Operations Complexity

// O(1) - Constant
array_push($arr, $val);          // Add to end
$arr[] = $val;                   // Add to end
$val = array_pop($arr);          // Remove from end

// O(n) - Linear
array_unshift($arr, $val);       // Add to beginning
array_shift($arr);               // Remove from beginning
in_array($needle, $arr);         // Search
array_search($needle, $arr);     // Search with key

// O(n log n) - Logarithmic
sort($arr);                      // Quicksort
usort($arr, $callback);          // Custom sort

// O(n²) - Quadratic (avoid in loops)
array_unique($arr);              // Remove duplicates

Database Query Optimization

// Use EXPLAIN to analyze queries
$stmt = $pdo->query("EXPLAIN SELECT * FROM users WHERE email = 'test@example.com'");

// Batch operations (faster than individual)
$pdo->beginTransaction();
foreach ($users as $user) {
    $stmt->execute([$user['name'], $user['email']]);
}
$pdo->commit();

// Use indexes for WHERE, ORDER BY, JOIN columns
CREATE INDEX idx_user_email ON users(email);
CREATE INDEX idx_created_at ON posts(created_at DESC);

22. Best Practices Quick Reference

Security Must-Haves

  • Prepared statements for all DB queries
  • password_hash() with PASSWORD_DEFAULT
  • CSRF tokens for state-changing operations
  • Input validation with filter_var()
  • Output escaping with htmlspecialchars()
  • HTTPS only for production

Code Quality

  • PSR-12 coding standard
  • Type declarations (parameter & return)
  • Dependency injection over tight coupling
  • Environment variables for config (.env)
  • Error logging to files, not screen
  • Unit tests for business logic (>80% coverage)

23. Laravel/Symfony Framework Essentials

Laravel Key Concepts

// Eloquent ORM
User::where('active', true)->get();              // Query builder
User::find(1);                                   // Find by ID
User::create(['name' => 'John']);                // Mass assignment

// Middleware
public function handle($request, Closure $next) {
    if (!$request->user()) {
        return redirect('login');
    }
    return $next($request);
}

// Service Container
app()->bind('PaymentGateway', function() {
    return new StripeGateway(config('stripe.key'));
});

Symfony Components

// Dependency Injection
class UserController {
    public function __construct(
        private UserRepository $users,
        private LoggerInterface $logger
    ) {}
}

// Event Dispatcher
$dispatcher->addListener('user.created', function($event) {
    // Send welcome email
});

24. Queue Systems & Background Jobs

Basic Queue Implementation

// Job class
class SendEmailJob {
    public function __construct(
        private string $email,
        private string $subject
    ) {}
    
    public function handle(Mailer $mailer): void {
        $mailer->send($this->email, $this->subject);
    }
}

// Dispatch job
$queue->push(new SendEmailJob($email, 'Welcome!'));

// Process queue (worker)
while ($job = $queue->pop()) {
    $job->handle($container->get(Mailer::class));
}

25. Critical Interview Topics Checklist

Before Your Interview Review:

  • Type system: scalar types, union types, nullable types
  • OOP concepts: inheritance, interfaces, traits, abstract classes
  • SOLID principles: practical examples in PHP
  • PSR standards: PSR-4 autoloading, PSR-12 coding style
  • Security: SQL injection, XSS, CSRF prevention
  • Performance: OpCache, query optimization, caching strategies
  • Testing: PHPUnit basics, mocking, assertions
  • Modern PHP: attributes, enums, readonly properties, match expressions
  • Database: transactions, indexes, prepared statements
  • API development: REST principles, authentication, rate limiting

Interview Success Tips:
• Explain your thought process while coding
• Mention security considerations proactively
• Discuss time/space complexity when relevant
• Know at least one PHP framework deeply
• Be ready to write code without IDE assistance

Found this useful? Pass it on.
Pro · $10/mo

The sheet is free. Pro goes deeper.

Pro opens the full question library behind every sheet, every refresher and a monthly AI allowance. One subscription, all formats.

Full question library All refreshers Cancel anytime