PHP
Updated: September 10, 2025Categories: 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, weakly typed language
- Embedded in HTML
- Runs on the server-side
- Widely used for web applications and backend development
- Supports object-oriented, procedural, and functional programming paradigms
Basic Syntax
PHP
12345678910<?php
// PHP code starts with <?php and ends with ?>
echo "Hello, World!"; // Print statement
// Single-line comment
/* Multi-line
comment */
// Semicolons are required to end statements
$variable = "Value"; // Variable declaration
Data Types
Primitive Types
PHP
123456789101112131415161718192021// Integers
$int1 = 42;
$int2 = -17;
// Floating-point numbers
$float = 3.14;
// Strings
$str1 = 'Single quotes';
$str2 = "Double quotes with {$variable} interpolation";
// Booleans
$bool1 = true;
$bool2 = false;
// Null
$null_var = null;
// Special type: Resource (database connections, file handles)
$file_handle = fopen('example.txt', 'r');
Collection Types
PHP
12345678910111213141516171819// 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]
]
];
Variables and Constants
PHP
1234567891011121314151617// 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;
// Superglobal variables
echo $_SERVER['REQUEST_METHOD']; // HTTP request method
echo $_GET['param']; // GET parameters
echo $_POST['username']; // POST parameters
Operators
Arithmetic Operators
PHP
123456789$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
Comparison Operators
PHP
123456789$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
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
123456789101112131415// If-Else
if ($condition) {
// Code
} elseif ($another_condition) {
// Code
} else {
// Code
}
// Ternary Operator
$result = $condition ? $value_if_true : $value_if_false;
// Null Coalescing Operator (PHP 7+)
$username = $_GET['user'] ?? 'Guest';
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
123456789101112131415161718192021222324// Basic Function
function greet($name) {
return "Hello, $name!";
}
// Function with Type Hints (PHP 7+)
function addNumbers(int $a, int $b): int {
return $a + $b;
}
// Anonymous Functions (Closures)
$multiply = function($a, $b) {
return $a * $b;
};
// Arrow Functions (PHP 7.4+)
$numbers = [1, 2, 3, 4];
$squared = array_map(fn($n) => $n ** 2, $numbers);
// Variable-length Arguments
function sum(...$numbers) {
return array_sum($numbers);
}
Object-Oriented Programming
Classes and Objects
PHP
12345678910111213141516171819202122232425262728293031323334353637383940414243class Person {
// Properties
public $name;
private $age;
// Constructor
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// Method
public function introduce() {
return "I'm {$this->name}, {$this->age} years old.";
}
}
// Object Creation
$person = new Person("John", 30);
echo $person->introduce();
// Inheritance
class Student extends Person {
public $school;
public function __construct($name, $age, $school) {
parent::__construct($name, $age);
$this->school = $school;
}
}
// Interfaces
interface Printable {
public function print();
}
// Traits (Multiple Inheritance Simulation)
trait Loggable {
public function log($message) {
echo $message;
}
}
Error Handling
PHP
1234567891011121314151617// Try-Catch
try {
// Code that might throw an exception
if ($error_condition) {
throw new Exception("An error occurred");
}
} catch (Exception $e) {
echo $e->getMessage();
} finally {
// Optional cleanup code
}
// Custom Error Handling
set_error_handler(function($errno, $errstr) {
// Custom error logic
});
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');
unlink('file.txt'); // Delete file
Database Connectivity (PDO)
PHP
12345678try {
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $pdo->query('SELECT * FROM users');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Web Development Features
PHP
123456789101112131415// Form Handling
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
// Session Management
session_start();
$_SESSION['user_id'] = $user->id;
// Cookies
setcookie('username', 'john_doe', time() + 3600);
// URL Redirection
header('Location: welcome.php');
exit();
Namespaces and Autoloading
PHP
1234567891011121314// Namespace Declaration
namespace MyApp\Models;
// Autoloading with Composer
// In composer.json:
// {
// "autoload": {
// "psr-4": {
// "MyApp\\": "src/"
// }
// }
// }
// Run: composer dump-autoload
Testing with PHPUnit
PHP
123456789use PHPUnit\Framework\TestCase;
class UserTest extends TestCase {
public function testUserCreation() {
$user = new User('john', 'password');
$this->assertInstanceOf(User::class, $user);
}
}
Modern PHP Features (PHP 8+)
PHP
123456789101112131415161718// Named Arguments
function createUser(string $name, int $age) { }
createUser(name: 'John', age: 30);
// Attributes
#[Route("/api/posts")]
class PostController { }
// Match Expression
$result = match($status) {
200 => 'OK',
404 => 'Not Found',
default => 'Unknown'
};
// Nullsafe Operator
$country = $user?->getAddress()?->getCountry();
Security Considerations
- Always sanitize and validate user inputs
- Use prepared statements for database queries
- Implement CSRF protection
- Use password_hash() for password storage
- Enable HTTPS
- Keep PHP and dependencies updated
Best Practices
- Use Composer for dependency management
- Follow PSR coding standards
- Use type hints and return type declarations
- Leverage modern PHP features
- Use framework-agnostic libraries
- Implement proper error logging
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/
- Laravel Framework: https://laravel.com/
- Symfony Framework: https://symfony.com/
Performance and Optimization Tips
- Use PHP 8+ for best performance
- Leverage opcache for bytecode caching
- Minimize database queries
- Use efficient algorithms
- Profile your code with Xdebug
- Consider using JIT compilation
Package Management with Composer
Bash
1234567# Install Composer globally
composer global require phpunit/phpunit
# Create new project
composer create-project symfony/skeleton my-project
# Add dependency
composer require symfony/http-client
Continue Learning
Discover more cheatsheets to boost your productivity