PHP Cheat Sheet
PHP is a widely used server-side scripting language designed for web development and general-purpose programming. This PHP cheatsheet is a structured, example-driven reference covering core syntax, arrays, functions, object-oriented features, and common PHP APIs.
Basic Script Structure
<?php
echo "Hello, PHP";
Running PHP
php script.php
Variables
$a = 10;
$b = "text";
$c = true;
Data Types
int
float
string
bool
array
object
null
gettype($a);
Strings
$s = "PHP";
strlen($s);
strtoupper($s);
strpos($s, "P");
$name = "World";
echo "Hello $name";
Operators
$a + $b;
$a - $b;
$a * $b;
$a / $b;
$a % $b;
$a == $b;
$a === $b;
$a != $b;
$a !== $b;
$a && $b;
$a || $b;
!$a;
Control Flow
if / else
if ($a > 10) {
$r = 1;
} else {
$r = 0;
}
switch
switch ($a) {
case 1:
break;
default:
break;
}
Loops
for ($i = 0; $i < 5; $i++) {
echo $i;
}
while ($a > 0) {
$a--;
}
foreach ($arr as $value) {
echo $value;
}
foreach ($arr as $key => $value) {
echo $key;
}
Functions
function add(int $a, int $b): int {
return $a + $b;
}
$r = add(2, 3);
Default Parameters
function multiply(int $a, int $b = 2): int {
return $a * $b;
}
Variadic Functions
function total(int ...$nums): int {
return array_sum($nums);
}
Arrays
Indexed Arrays
$arr = [1, 2, 3];
$arr[] = 4;
Associative Arrays
$map = [
"a" => 1,
"b" => 2
];
Array Functions
count($arr);
array_push($arr, 5);
array_pop($arr);
array_map(fn($n) => $n * 2, $arr);
array_filter($arr, fn($n) => $n > 1);
Classes
class Counter {
private int $value = 0;
public function increment(): void {
$this->value++;
}
public function get(): int {
return $this->value;
}
}
Creating Objects
$c = new Counter();
$c->increment();
Constructors
class Point {
public function __construct(
public int $x,
public int $y
) {}
}
Inheritance
class Animal {
public function speak() {}
}
class Dog extends Animal {
}
Interfaces
interface Logger {
public function log(string $msg): void;
}
class ConsoleLogger implements Logger {
public function log(string $msg): void {
echo $msg;
}
}
Abstract Classes
abstract class Shape {
abstract public function area(): float;
}
Traits
trait Timestamped {
public function now(): int {
return time();
}
}
class Item {
use Timestamped;
}
Namespaces
namespace App\Utils;
function add(int $a, int $b): int {
return $a + b;
}
use App\Utils;
Exceptions
try {
throw new Exception("fail");
} catch (Exception $e) {
echo $e->getMessage();
} finally {
}
File I/O
file_put_contents("file.txt", "text");
$content = file_get_contents("file.txt");
JSON
$data = ["a" => 1];
$json = json_encode($data);
$decoded = json_decode($json, true);
Date & Time
$date = new DateTime();
echo $date->format("Y-m-d");
Superglobals
$_GET;
$_POST;
$_SERVER;
$_SESSION;
$_COOKIE;