PHP Fundamentals Cheatsheet
PHP Syntax
Section titled “PHP Syntax”PHP Tags
Section titled “PHP Tags”<?php echo "Standard tag"; ?><?= "Short echo tag" ?>Statement Rules
Section titled “Statement Rules”- Every statement ends with a semicolon (
;) - Variables are case-sensitive (
$name≠$Name) - Functions/keywords are case-insensitive (
echo=ECHO)
Comments
Section titled “Comments”// Single-line comment# Also single-line/* Multi-line comment *//** PHPDoc comment */Variables
Section titled “Variables”Declaration
Section titled “Declaration”$name = "John"; // String$age = 25; // Integer$price = 19.99; // Float$isActive = true; // Boolean$items = [1, 2, 3]; // ArrayNaming Rules
Section titled “Naming Rules”- Must start with
$followed by letter or underscore - Can contain letters, numbers, underscores
- Cannot start with a number or contain hyphens
$global = "accessible everywhere with global keyword";
function example() { global $global; // Access global variable $local = "only here"; // Local to function static $count = 0; // Persists between calls $count++;}References
Section titled “References”$a = 5;$b = &$a; // $b references $a$b = 10; // $a is now also 10Constants
Section titled “Constants”Defining Constants
Section titled “Defining Constants”// Using define() - can be used anywheredefine('SITE_NAME', 'My Website');define('COLORS', ['red', 'green', 'blue']); // PHP 7+
// Using const - must be at top levelconst MAX_USERS = 100;const TAX_RATE = 0.08;Checking & Accessing
Section titled “Checking & Accessing”if (defined('SITE_NAME')) { echo SITE_NAME;}Magic Constants
Section titled “Magic Constants”| Constant | Description |
|---|---|
__FILE__ | Full path of current file |
__DIR__ | Directory of current file |
__LINE__ | Current line number |
__FUNCTION__ | Current function name |
__CLASS__ | Current class name |
__METHOD__ | Current class method |
Arrays
Section titled “Arrays”Indexed Arrays
Section titled “Indexed Arrays”$fruits = ["apple", "banana", "orange"];echo $fruits[0]; // apple$fruits[] = "grape"; // Add to endAssociative Arrays
Section titled “Associative Arrays”$user = [ "name" => "John", "age" => 30, "email" => "john@example.com"];echo $user["name"]; // JohnMultidimensional Arrays
Section titled “Multidimensional Arrays”$products = [ "laptop" => ["price" => 800, "qty" => 5], "mouse" => ["price" => 25, "qty" => 20]];echo $products["laptop"]["price"]; // 800Looping
Section titled “Looping”// Indexedforeach ($fruits as $fruit) { echo $fruit;}
// Associative (key => value)foreach ($user as $key => $value) { echo "$key: $value";}Common Array Functions
Section titled “Common Array Functions”| Function | Description |
|---|---|
count($arr) | Get array length |
in_array($val, $arr) | Check if value exists |
array_push($arr, $val) | Add to end |
array_pop($arr) | Remove from end |
array_merge($a, $b) | Merge arrays |
array_keys($arr) | Get all keys |
array_values($arr) | Get all values |
sort($arr) | Sort array |
Strings
Section titled “Strings”Single vs Double Quotes (Single-line)
Section titled “Single vs Double Quotes (Single-line)”$name = "PHP";
// Single quotes: literal (no parsing)echo 'Hello $name'; // Hello $name
// Double quotes: variable interpolationecho "Hello $name"; // Hello PHPecho "Hello {$name}!"; // Hello PHP! (explicit syntax)Heredoc & Nowdoc (Multi-line Strings)
Section titled “Heredoc & Nowdoc (Multi-line Strings)”// Heredoc - parses variables (like double quotes)$html = <<<HTML<h1>Welcome, $name!</h1><p>This can span multiple lines</p>HTML;
// Nowdoc - literal (like single quotes)$js = <<<'JS'console.log('$name not parsed');// Also supports multiple linesJS;Concatenation
Section titled “Concatenation”$greeting = "Hello" . " " . "World"; // Hello World$greeting .= "!"; // Hello World!Common String Functions
Section titled “Common String Functions”| Function | Description |
|---|---|
strlen($str) | String length |
strtoupper($str) | Convert to uppercase |
strtolower($str) | Convert to lowercase |
substr($str, 0, 5) | Extract substring |
str_replace("a", "b", $str) | Replace text |
trim($str) | Remove whitespace |
explode(",", $str) | Split string to array |
implode(",", $arr) | Join array to string |
Functions
Section titled “Functions”Basic Declaration
Section titled “Basic Declaration”function greet($name) { return "Hello, $name!";}echo greet("John"); // Hello, John!Default Parameters
Section titled “Default Parameters”function greet($name = "Guest", $greeting = "Hello") { return "$greeting, $name!";}greet(); // Hello, Guest!greet("John"); // Hello, John!greet("John", "Hi"); // Hi, John!Pass by Reference
Section titled “Pass by Reference”function increment(&$value) { $value++;}$num = 5;increment($num);echo $num; // 6Variadic Parameters
Section titled “Variadic Parameters”function sum(...$numbers) { return array_sum($numbers);}echo sum(1, 2, 3, 4); // 10Type Hints (PHP 7+)
Section titled “Type Hints (PHP 7+)”// Parameter type hintsfunction greet(string $name): void { echo "Hello, $name!";}
// Multiple types with return typefunction add(int $a, int $b): int { return $a + $b;}
// Nullable types (PHP 7.1+)function findUser(?int $id): ?array { return $id ? ['id' => $id] : null;}
// Union types (PHP 8+)function process(int|float $value): int|float { return $value * 2;}Common Type Hints: string, int, float, bool, array, object, mixed, void, null
Named Arguments (PHP 8+)
Section titled “Named Arguments (PHP 8+)”function createUser($name, $email, $age = null) { }
createUser(name: "John", email: "john@test.com");Quick Reference Tables
Section titled “Quick Reference Tables”Type Checking Functions
Section titled “Type Checking Functions”| Function | Checks for |
|---|---|
is_string($var) | String |
is_int($var) | Integer |
is_float($var) | Float |
is_bool($var) | Boolean |
is_array($var) | Array |
is_null($var) | Null |
isset($var) | Variable exists and not null |
empty($var) | Empty value |
Math Functions
Section titled “Math Functions”| Function | Description |
|---|---|
abs($n) | Absolute value |
round($n) | Round number |
ceil($n) | Round up |
floor($n) | Round down |
max($a, $b) | Maximum value |
min($a, $b) | Minimum value |
rand($min, $max) | Random number |
Date Functions
Section titled “Date Functions”echo date('Y-m-d'); // 2024-01-15echo date('H:i:s'); // 14:30:00echo time(); // Unix timestampecho strtotime('+1 week'); // Timestamp in 1 week