
PHP Cheatsheet
33 of 33 code examples
Hello World
Basic PHP script
Basics<?php
echo "Hello, World!";
?>
Variables
Variable declarations
Basics<?php
$name = "John";
$age = 30;
$price = 19.99;
$is_active = true;
// Constants
define("PI", 3.14159);
const MAX_USERS = 1000;
?>
Data Types
PHP data types
Basics<?php
// Scalar types
$string = "Hello";
$integer = 42;
$float = 3.14;
$boolean = true;
// Compound types
$array = [1, 2, 3];
$object = new stdClass();
// Special types
$null = null;
$resource = fopen("file.txt", "r");
?>
Strings
String operations
Basics<?php
$text = "Hello World";
// Concatenation
$greeting = "Hello" . " " . "World";
// String functions
$length = strlen($text);
$upper = strtoupper($text);
$lower = strtolower($text);
$position = strpos($text, "World");
$replaced = str_replace("World", "PHP", $text);
// String interpolation
$name = "John";
echo "Hello $name";
echo "Hello {$name}";
?>
Arrays
Array operations
Data Structures<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];
$fruits[] = "grape";
// Associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
// Array functions
$count = count($fruits);
$last = array_pop($fruits);
$first = array_shift($fruits);
$merged = array_merge($fruits, ["mango"]);
// Iteration
foreach ($person as $key => $value) {
echo "$key: $value
";
}
?>
Control Structures
If, loops, switch
Basics<?php
// If statement
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
}
// For loop
for ($i = 0; $i < 10; $i++) {
echo $i;
}
// Foreach loop
foreach ($fruits as $fruit) {
echo $fruit;
}
// Switch
switch ($day) {
case "Monday":
echo "Start of week";
break;
case "Friday":
echo "Weekend soon!";
break;
default:
echo "Regular day";
}
?>
Functions
Function definitions
Functions<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
// Default parameters
function multiply($a, $b = 2) {
return $a * $b;
}
// Variable arguments
function sum(...$numbers) {
return array_sum($numbers);
}
// Type declarations
function add(int $a, int $b): int {
return $a + $b;
}
// Anonymous function
$square = function($n) {
return $n * $n;
};
?>
Classes & Objects
OOP in PHP
OOP<?php
class Person {
// Properties
public $name;
private $age;
protected $email;
// Constructor
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// Methods
public function introduce() {
return "Hello, I'm {$this->name}";
}
// Getter/Setter
public function getAge() {
return $this->age;
}
}
// Usage
$person = new Person("Alice", 25);
echo $person->introduce();
?>
Inheritance
Class inheritance
OOP<?php
class Animal {
public function speak() {
return "Some sound";
}
}
class Dog extends Animal {
public function speak() {
return "Woof!";
}
}
class Cat extends Animal {
public function speak() {
return "Meow!";
}
}
// Usage
$dog = new Dog();
echo $dog->speak(); // Woof!
?>
Interfaces
Interface implementation
OOP<?php
interface Logger {
public function log($message);
}
interface EmailSender {
public function send($to, $subject, $body);
}
class FileLogger implements Logger {
public function log($message) {
file_put_contents('log.txt', $message, FILE_APPEND);
}
}
class EmailService implements Logger, EmailSender {
public function log($message) {
// Log to email
}
public function send($to, $subject, $body) {
// Send email
}
}
?>
Traits
Code reuse with traits
OOP<?php
trait Loggable {
public function log($message) {
echo "Log: $message";
}
}
trait Timestampable {
public function getTimestamp() {
return date('Y-m-d H:i:s');
}
}
class User {
use Loggable, Timestampable;
public function create() {
$this->log("User created at " . $this->getTimestamp());
}
}
// Usage
$user = new User();
$user->create();
?>
Error Handling
Exceptions and errors
Error Handling<?php
// Basic try-catch
try {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Cannot divide by zero";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Custom exception
class ValidationException extends Exception {
public function __construct($message, $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
}
// Throwing exceptions
function validateEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new ValidationException("Invalid email format");
}
return true;
}
?>
File Handling
File operations
I/O<?php
// Reading files
$content = file_get_contents('file.txt');
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);
// Writing files
file_put_contents('output.txt', 'Hello World');
// File operations
if (file_exists('file.txt')) {
$size = filesize('file.txt');
$modified = filemtime('file.txt');
}
// Directory operations
$files = scandir('.');
foreach ($files as $file) {
if (is_file($file)) {
echo $file . "
";
}
}
?>
Forms Handling
Processing form data
Web<?php
// Handling POST data
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$message = $_POST['message'] ?? '';
// Validation
if (empty($name) || empty($email)) {
$error = "Name and email are required";
} else {
// Process form
echo "Thank you, $name!";
}
}
// Handling GET data
$page = $_GET['page'] ?? 1;
$search = $_GET['search'] ?? '';
?>
Sessions
Session management
Web<?php
// Start session
session_start();
// Set session variables
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
$_SESSION['logged_in'] = true;
// Access session data
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in']) {
echo "Welcome, " . $_SESSION['username'];
}
// Destroy session
session_destroy();
?>
Cookies
Cookie handling
Web<?php
// Set cookie
setcookie('user_preference', 'dark_mode', time() + (86400 * 30), "/");
// Read cookie
$preference = $_COOKIE['user_preference'] ?? 'light_mode';
// Delete cookie
setcookie('user_preference', '', time() - 3600, "/");
// Secure cookie
setcookie('secure_cookie', 'value', [
'expires' => time() + 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
?>
Database - MySQLi
MySQL database operations
Database<?php
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query execution
$result = $conn->query("SELECT * FROM users WHERE active = 1");
// Fetch data
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . ", Email: " . $row['email'];
}
// Prepared statements
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$name = "John";
$email = "john@example.com";
$stmt->execute();
// Close connection
$conn->close();
?>
Database - PDO
PDO database operations
Database<?php
try {
// PDO connection
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Query with PDO
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Prepared statement
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->execute([
':name' => 'Alice',
':email' => 'alice@example.com'
]);
// Transaction
$pdo->beginTransaction();
// Multiple operations...
$pdo->commit();
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
JSON Handling
JSON encoding and decoding
Data Formats<?php
// Array to JSON
$data = [
'name' => 'John',
'age' => 30,
'cities' => ['New York', 'London']
];
$json = json_encode($data);
// JSON to array
$array = json_decode($json, true);
// JSON from API
$api_url = 'https://api.example.com/users';
$response = file_get_contents($api_url);
$users = json_decode($response, true);
// JSON response
header('Content-Type: application/json');
echo json_encode(['status' => 'success', 'data' => $users]);
?>
Regular Expressions
Pattern matching with regex
Advanced<?php
// Basic pattern matching
$pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/';
$email = 'test@example.com';
if (preg_match($pattern, $email)) {
echo "Valid email";
}
// Find all matches
$text = "The prices are $10, $20, and $30";
preg_match_all('/$d+/', $text, $matches);
// Replace with regex
$text = "Hello World";
$new_text = preg_replace('/World/', 'PHP', $text);
// Split with regex
$words = preg_split('/s+/', "Hello World PHP");
?>
Date and Time
Date manipulation
Utilities<?php
// Current date/time
$now = date('Y-m-d H:i:s');
$timestamp = time();
// Create from string
$date = new DateTime('2024-01-15');
$date->modify('+1 day');
// Format dates
echo $date->format('Y-m-d'); // 2024-01-16
echo date('l, F j, Y'); // Monday, January 15, 2024
// Date difference
$date1 = new DateTime('2024-01-01');
$date2 = new DateTime('2024-01-15');
$interval = $date1->diff($date2);
echo $interval->days; // 14
// Timezone
$timezone = new DateTimeZone('America/New_York');
$date = new DateTime('now', $timezone);
?>
File Upload
Handling file uploads
Web<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$file = $_FILES['file'];
// Check for errors
if ($file['error'] === UPLOAD_ERR_OK) {
// Validate file type
$allowed_types = ['image/jpeg', 'image/png', 'application/pdf'];
if (in_array($file['type'], $allowed_types)) {
// Validate file size (2MB max)
if ($file['size'] <= 2 * 1024 * 1024) {
// Generate unique filename
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '.' . $extension;
$upload_path = 'uploads/' . $filename;
// Move uploaded file
if (move_uploaded_file($file['tmp_name'], $upload_path)) {
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
} else {
echo "File too large.";
}
} else {
echo "Invalid file type.";
}
} else {
echo "Upload error: " . $file['error'];
}
}
?>
cURL
HTTP requests with cURL
Web<?php
// Basic GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// POST request with JSON
$data = ['name' => 'John', 'email' => 'john@example.com'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/users');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// With headers and timeout
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.example.com/data',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer token123',
'User-Agent: MyApp/1.0'
]
]);
?>
Composer & Autoloading
Package management
Packages<?php
// Composer autoload
require 'vendor/autoload.php';
// Using installed packages
use GuzzleHttpClient;
use MonologLogger;
use MonologHandlerStreamHandler;
// Create logger
$log = new Logger('name');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));
// Use HTTP client
$client = new Client();
$response = $client->request('GET', 'https://api.example.com/data');
// Custom autoloader
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});
// Using namespaces
namespace MyAppControllers;
class UserController {
public function index() {
return "User list";
}
}
?>
Magic Methods
PHP magic methods
OOP<?php
class MagicClass {
private $data = [];
// __get and __set
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
// __call for method overloading
public function __call($name, $arguments) {
echo "Calling method '$name' with arguments: " . implode(', ', $arguments);
}
// __toString
public function __toString() {
return "MagicClass instance";
}
// __invoke
public function __invoke($param) {
echo "Object called as function with: $param";
}
}
$obj = new MagicClass();
$obj->name = "John"; // Uses __set
echo $obj->name; // Uses __get
$obj->unknownMethod("test"); // Uses __call
echo $obj; // Uses __toString
$obj("hello"); // Uses __invoke
?>
Array Functions
Common array operations
Data Structures<?php
$numbers = [1, 2, 3, 4, 5];
$users = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30]
];
// Array mapping
$squared = array_map(fn($n) => $n * $n, $numbers);
// Array filtering
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
// Array reducing
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
// Array sorting
sort($numbers); // by values
asort($users); // associative by values
ksort($users); // by keys
// Array searching
$hasThree = in_array(3, $numbers);
$key = array_search('John', array_column($users, 'name'));
// Array column
$names = array_column($users, 'name');
// Array chunking
$chunks = array_chunk($numbers, 2);
?>
String Functions
Advanced string operations
Basics<?php
$text = "Hello World, welcome to PHP programming";
// String splitting
$words = explode(" ", $text);
$parts = str_split($text, 5);
// String joining
$sentence = implode("-", $words);
// String formatting
$formatted = sprintf("Name: %s, Age: %d", "John", 25);
// String trimming
$trimmed = trim(" Hello World ");
$left = ltrim(" Hello");
$right = rtrim("Hello ");
// String encoding
$html = htmlspecialchars("<div>Hello</div>");
$url = urlencode("Hello World & PHP");
// String comparison
$compare = strcmp("hello", "hello"); // 0
$caseCompare = strcasecmp("HELLO", "hello"); // 0
// String padding
$padded = str_pad("Hello", 10, "-", STR_PAD_BOTH);
?>
Type Juggling
PHP type conversion
Basics<?php
// Automatic type conversion
$string = "10";
$number = 5;
$result = $string + $number; // 15
// Type casting
$int = (int) "123";
$float = (float) "3.14";
$string = (string) 456;
$bool = (bool) 1;
$array = (array) "hello";
// Strict comparison
$strict = "10" === 10; // false
$loose = "10" == 10; // true
// Type checking
$isString = is_string("hello");
$isInt = is_int(123);
$isArray = is_array([1, 2, 3]);
$isObject = is_object(new stdClass());
// Type functions
$type = gettype($variable);
$var_dump = var_export($array, true);
?>
Global Variables
PHP superglobals
Web<?php
// $_GET - URL parameters
$page = $_GET['page'] ?? 1;
// $_POST - Form data
$name = $_POST['name'] ?? '';
// $_SESSION - Session data
session_start();
$user_id = $_SESSION['user_id'] ?? null;
// $_COOKIE - Cookie data
$theme = $_COOKIE['theme'] ?? 'light';
// $_SERVER - Server info
$method = $_SERVER['REQUEST_METHOD'];
$ip = $_SERVER['REMOTE_ADDR'];
$agent = $_SERVER['HTTP_USER_AGENT'];
// $_FILES - File uploads
$file = $_FILES['upload'] ?? null;
// $_ENV - Environment variables
$db_host = $_ENV['DB_HOST'] ?? 'localhost';
// $GLOBALS - All global variables
$GLOBALS['config'] = ['debug' => true];
?>
Password Hashing
Secure password handling
Security<?php
// Password hashing
$password = "mysecretpassword";
$hash = password_hash($password, PASSWORD_DEFAULT);
// Verify password
if (password_verify($password, $hash)) {
echo "Password is valid!";
} else {
echo "Invalid password!";
}
// Check if hash needs rehashing
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
$newHash = password_hash($password, PASSWORD_DEFAULT);
}
// Generate random password
$randomPassword = bin2hex(random_bytes(8));
// Password strength validation
function isStrongPassword($password) {
return strlen($password) >= 8 &&
preg_match('/[A-Z]/', $password) &&
preg_match('/[a-z]/', $password) &&
preg_match('/[0-9]/', $password) &&
preg_match('/[^A-Za-z0-9]/', $password);
}
?>
PHP Filters
Input validation and sanitization
Security<?php
// Validate email
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
}
// Sanitize string
$dirty = "<script>alert('xss')</script>Hello";
$clean = filter_var($dirty, FILTER_SANITIZE_STRING);
// Validate URL
$url = "https://example.com";
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "Valid URL";
}
// Validate IP address
$ip = "192.168.1.1";
if (filter_var($ip, FILTER_VALIDATE_IP)) {
echo "Valid IP";
}
// Validate integer range
$age = 25;
if (filter_var($age, FILTER_VALIDATE_INT,
["options" => ["min_range" => 1, "max_range" => 120]])) {
echo "Valid age";
}
// Sanitize email
$email = "john@example.com";
$sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);
?>
Generators
Memory-efficient iterators
Advanced<?php
// Simple generator
function numberGenerator($max) {
for ($i = 1; $i <= $max; $i++) {
yield $i;
}
}
// Using generator
foreach (numberGenerator(1000000) as $number) {
echo $number . "
";
}
// Key-value generator
function keyValueGenerator() {
yield 'name' => 'John';
yield 'age' => 30;
yield 'city' => 'New York';
}
// Using key-value generator
foreach (keyValueGenerator() as $key => $value) {
echo "$key: $value
";
}
// Memory efficient file reading
function readLargeFile($filename) {
$file = fopen($filename, 'r');
while (!feof($file)) {
yield fgets($file);
}
fclose($file);
}
// Using file generator
foreach (readLargeFile('large_file.txt') as $line) {
echo $line;
}
?>
Closures & Arrow Functions
Anonymous functions
Functions<?php
// Basic closure
$greet = function($name) {
return "Hello, $name!";
};
echo $greet("John");
// Closure with use
$prefix = "Mr. ";
$formalGreet = function($name) use ($prefix) {
return "Hello, $prefix$name!";
};
// Arrow functions (PHP 7.4+)
$add = fn($a, $b) => $a + $b;
$square = fn($n) => $n * $n;
// Using array functions with closures
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(fn($n) => $n * $n, $numbers);
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
// Closure as callback
usort($numbers, fn($a, $b) => $a <=> $b);
// Self-executing closure
$result = (function($x, $y) {
return $x + $y;
})(5, 3);
?>