Loading...

PHP Cheat Sheet

The PHP Cheat Sheet is a concise yet comprehensive reference guide designed for developers to quickly access PHP’s core functionalities, syntax, and best practices. It serves as an essential tool for both learning and professional development, allowing developers to efficiently implement complex algorithms, data structures, and object-oriented programming (OOP) principles. Its importance lies in enabling fast problem-solving, preventing common coding errors, and ensuring adherence to industry-standard PHP conventions.
Developers can use the PHP Cheat Sheet throughout the software development lifecycle—from writing simple scripts to architecting large-scale applications. It covers key PHP concepts including array and string manipulations, control structures, functions, classes, inheritance, interfaces, traits, and exception handling. By referencing this cheat sheet, developers can reinforce their understanding of syntax rules, optimize algorithm performance, and ensure their codebase remains maintainable and secure.
Readers of this PHP Cheat Sheet will gain practical knowledge for applying PHP in real-world projects. They will learn how to structure code efficiently, leverage OOP principles to design scalable systems, and implement robust error-handling mechanisms. Additionally, it provides insights into performance optimization, security considerations, and common pitfalls to avoid, making it a crucial resource for software architects, backend engineers, and advanced PHP programmers seeking to build reliable and high-performing applications.

Basic Example

php
PHP Code
<?php
// Simple PHP array and iteration demonstrating core syntax
$user = [
'name' => 'Alice',
'age' => 28,
'role' => 'Developer'
];

function displayUser(array $user): void {
foreach ($user as $key => $value) {
echo ucfirst($key) . ": " . $value . PHP_EOL;
}
}

// Execute function
displayUser($user);
?>

Within the function, a foreach loop iterates over the array, and ucfirst capitalizes the first letter of each key, improving readability of the output. PHP_EOL is used for cross-platform line breaks, ensuring consistency across different operating systems. This example also illustrates fundamental PHP Cheat Sheet concepts, such as array manipulation, function declaration, type hinting, and proper output formatting.
From a practical perspective, such a function can be extended to handle more complex datasets or integrated with database query results. It reflects professional coding practices, emphasizing clarity, maintainability, and adherence to PHP conventions while serving as a foundational reference for applying cheat sheet concepts in actual projects.

Practical Example

php
PHP Code
<?php
// Object-oriented user management with PHP
class User {
private string $name;
private int $age;
private string $role;

public function __construct(string $name, int $age, string $role) {
$this->name = $name;
$this->age = $age;
$this->role = $role;
}

public function getInfo(): string {
return "Name: {$this->name}, Age: {$this->age}, Role: {$this->role}";
}
}

$users = [
new User('Bob', 32, 'Engineer'),
new User('Carol', 29, 'Architect')
];

foreach ($users as $user) {
echo $user->getInfo() . PHP_EOL;
}
?>

Advanced PHP Implementation

php
PHP Code
<?php
// Advanced example: OOP, exception handling, and performance optimization
class Calculator {
public function divide(float $a, float $b): float {
if ($b === 0.0) {
throw new InvalidArgumentException("Division by zero is not allowed.");
}
return $a / $b;
}
}

try {
$calc = new Calculator();
echo $calc->divide(100, 4) . PHP_EOL;
echo $calc->divide(10, 0) . PHP_EOL; // Will trigger exception
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
}
?>

The advanced example demonstrates PHP Cheat Sheet principles in a real-world context. The Calculator class encapsulates division logic and includes a runtime check for zero divisors, throwing an InvalidArgumentException when needed. The try/catch block implements structured exception handling, ensuring the application continues running safely after encountering errors.

Adhering to PHP best practices is essential for building efficient and reliable applications. Key recommendations include using strict typing and type hints, selecting appropriate data structures, implementing efficient algorithms, and following OOP design patterns. Common pitfalls to avoid include memory leaks, unhandled exceptions, inefficient loops, and unvalidated inputs.

📊 Comprehensive Reference

PHP Element/Method Description Syntax Example Notes
echo Output string echo "text"; echo "Hello"; Prints text
print Output string and returns 1 print "text"; print "Hello"; Returns 1
array Create array array(1,2,3) $arr = array(1,2,3); Alternative: []
count Array count count($arr); count($arr); Get number of elements
foreach Array iteration foreach($arr as $val) foreach($arr as $val) echo $val; Common for loops
isset Check variable existence isset($var); isset($name); Boolean return
empty Check if variable empty empty($var); empty($name); Includes null,0,""
array_push Append to array array_push($arr,$val); array_push($arr,4); Adds element at end
array_pop Pop last element array_pop($arr); array_pop($arr); Returns removed element
explode Split string to array explode(" ",$str); explode(" ","a b"); Text processing
implode Join array to string implode(",",$arr); implode(",",[1,2]); For CSV/text output
strlen String length strlen($str); strlen("Hello"); Includes spaces
substr Substring substr($str,0,5); substr("abcdef",0,3); Extract substring
str_replace String replacement str_replace("a","b",$str); str_replace("a","b","abc"); Text handling
json_encode Array to JSON json_encode($arr); json_encode(["a"=>1]); API use
json_decode JSON to array json_decode($str,true); json_decode('{"a":1}',true); Parsing data
file_get_contents Read file file_get_contents("file.txt"); file_get_contents("data.txt"); Simple file read
file_put_contents Write file file_put_contents("file.txt",$data); file_put_contents("data.txt","abc"); Overwrite content
fopen Open file fopen("file.txt","r"); fopen("data.txt","r"); Used with fread/fwrite
fclose Close file fclose($handle); fclose($fp); Release resource
date Format date date("Y-m-d"); date("Y-m-d"); Can combine time()
time Current timestamp time(); time(); Seconds since epoch
strtotime Convert string to timestamp strtotime("next Monday"); strtotime("2025-10-01"); Scheduling
session_start Start session session_start(); session_start(); Cross-page storage
session_destroy Destroy session session_destroy(); session_destroy(); Clear session data
setcookie Set cookie setcookie("name","value"); setcookie("user","php"); Session management
header Send HTTP header header("Location: url"); header("Location: /home"); Page redirect
require Include file required "file.php"; require "config.php"; Fatal error if missing
include Include file include "file.php"; include "header.php"; Warning if missing
require_once Include once required_once "file.php"; require_once "config.php"; Prevent duplication
include_once Include once include_once "file.php"; include_once "header.php"; Prevent duplication
function Declare function function name(){} function test(){} Supports type hints
return Return value return $val; return 5; End function execution
class Define class class Name{} class User{} OOP basics
public Public property/method public $var; public $name; Accessible externally
private Private property/method private $var; private $age; Class internal only
protected Protected property/method protected $var; protected $role; Accessible in subclasses
__construct Constructor function __construct(){} function __construct($a){} Initialize object
__destruct Destructor function __destruct(){} function __destruct(){} Resource cleanup
try/catch Exception handling try{}catch(Exception $e){} try{}catch(Exception $e){} Structured error management
throw Throw exception throw new Exception("msg"); throw new Exception("Error"); Exception mechanism
spl_autoload_register Autoload class spl_autoload_register(fn($c)=>include "$c.php"); spl_autoload_register(fn($c)=>include "$c.php"); Manage class files
var_dump Debug output var_dump($var); var_dump($user); View type and value
print_r Array/Object debug print_r($arr); print_r($users); Readable format
isset Variable exists isset($var); isset($name); Boolean
empty Variable empty empty($var); empty($name); Boolean
die Terminate script die("msg"); die("Error"); Immediate exit
exit Terminate script exit("msg"); exit("Exit"); Immediate exit
htmlspecialchars Escape HTML htmlspecialchars("<a>"); htmlspecialchars("<b>"); Prevent XSS
trim Trim spaces trim(" abc "); trim(" abc "); Clean input
array_key_exists Check key array_key_exists("a",$arr); array_key_exists("a",["a"=>1]); Key existence
method_exists Check method method_exists($obj,"func"); method_exists($user,"getInfo"); Avoid errors
class_exists Check class class_exists("User"); class_exists("User"); Dynamic checks
interface_exists Check interface interface_exists("IUser"); interface_exists("IUser"); Dynamic checks
trait_exists Check trait trait_exists("T"); trait_exists("T"); Code reuse
ob_start Start output buffer ob_start(); ob_start(); Performance optimization
ob_get_clean Get and clean buffer ob_get_clean(); ob_get_clean(); Output control
uniqid Generate unique ID uniqid(); uniqid(); Quick unique identifiers
mt_rand Random number mt_rand(1,10); mt_rand(1,10); Faster than rand()
shuffle Shuffle array shuffle($arr); shuffle([1,2,3]); Randomization
in_array Value in array in_array(3,$arr); in_array(3,[1,2,3]); Boolean
array_merge Merge arrays array_merge($a,$b); array_merge([1],[2]); Combine arrays
sort Sort array sort($arr); sort([3,1,2]); Ascending order
rsort Reverse sort rsort($arr); rsort([3,1,2]); Descending order
asort Sort assoc asort($arr); asort(["b"=>2,"a"=>1]); Maintains keys
ksort Sort keys ksort($arr); ksort(["b"=>2,"a"=>1]); Ascending keys
arsort Reverse assoc arsort($arr); arsort(["b"=>2,"a"=>1]); Descending keys
krsort Reverse keys krsort($arr); krsort(["b"=>2,"a"=>1]); Descending keys
explode Split string explode(",","a,b"); explode(",","1,2,3"); Create array
implode Join array implode(",",$arr); implode(",",[1,2]); To string
substr Substring substr("abcdef",0,3); substr("abcdef",0,3); String slice
str_replace Replace string str_replace("a","b",$str); str_replace("a","b","abc"); Text replacement
preg_match Regex match preg_match("/\d/",$str); preg_match("/\d/","123"); Boolean
preg_replace Regex replace preg_replace("/a/","b",$str); preg_replace("/a/","b","abc"); Text replacement
array_filter Filter array array_filter($arr, fn($v)=>$v>1); array_filter([1,2,3],fn($v)=>$v>1); Callback
array_map Map array array_map(fn($v)=>$v*2,$arr); array_map(fn($v)=>$v*2,[1,2]); Callback
array_reduce Reduce array array_reduce($arr, fn($c,$v)=>$c+$v,0); array_reduce([1,2,3],fn($c,$v)=>$c+$v,0); Aggregate
password_hash Hash password password_hash($pwd,PASSWORD_DEFAULT); password_hash("123",PASSWORD_DEFAULT); Secure
password_verify Verify hash password_verify($pwd,$hash); password_verify("123",$hash); Authentication
filter_var Validate data filter_var($email,FILTER_VALIDATE_EMAIL); filter_var("[[email protected]](mailto:[email protected])",FILTER_VALIDATE_EMAIL); Sanitize/validate
microtime Current time microtime(true); microtime(true); Performance checks
ceil Round up ceil(4.2); ceil(4.2); Math function
floor Round down floor(4.8); floor(4.8); Math function
round Round nearest round(4.5); round(4.5); Math function
abs Absolute value abs(-5); abs(-5); Math function

📊 Complete PHP Properties Reference

Property Values Default Description PHP Support
memory_limit Integer string 128M Maximum memory usage
error_reporting Integer E_ALL Level of error reporting All PHP versions
display_errors On/Off On Display errors to screen All PHP versions
max_execution_time Integer 30 Maximum script execution time All PHP versions
upload_max_filesize Integer string 2M Maximum uploaded file size
post_max_size Integer string 8M Maximum POST size
default_charset String UTF-8 Default character encoding PHP 5.6+
date.timezone String UTC Default timezone PHP 5.1+
session.gc_maxlifetime Integer 1440 Session garbage collection time All PHP versions
opcache.enable On/Off Off Enable OPcache PHP 5.5+
max_input_vars Integer 1000 Maximum input variables PHP 5.3+
precision Integer 14 Floating point precision All PHP versions

In summary, mastering the PHP Cheat Sheet empowers developers to write efficient, secure, and maintainable code. It reinforces fundamental PHP concepts, OOP principles, algorithmic thinking, and real-world data structure usage. This resource is pivotal in bridging the gap between basic PHP knowledge and advanced, production-ready development practices. For continued learning, developers should explore PHP frameworks such as Laravel or Symfony, delve deeper into design patterns, optimize database interactions, and study advanced security techniques. Applying these principles consistently ensures robust, high-performing PHP applications and professional code quality across projects.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

4
Questions
🎯
70%
To Pass
♾️
Time
🔄
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top