๐ PHP Cheat Sheet
Quick reference for syntax, functions & patterns
๐ PHP Tags & Output
<?php echo "text"; ?>
<?= "shorthand echo" ?>
print "hello";
printf("%.2f", 3.14);
var_dump($x); // type + value
print_r($arr); // readable array
$x = sprintf("%.2f", 1.5); // return string
๐ฆ String Functions
strlen($s) // length
strtolower / strtoupper
str_contains($s, $q) // PHP 8
str_starts_with / str_ends_with
str_replace($f, $r, $s)
substr($s, $start, $len)
strpos($s, $needle)
trim / ltrim / rtrim
explode(",", $s) โ array
implode(",", $arr) โ string
sprintf("%.2f", 3.14)
number_format(1234.5, 2)
๐ Array Functions
count($a)
array_push($a, $v) / $a[] = $v
array_pop / array_shift / array_unshift
array_merge($a, $b)
array_slice($a, $s, $l)
array_map($fn, $a)
array_filter($a, $fn)
array_reduce($a, $fn, $init)
array_search($val, $a)
in_array($val, $a, true)
array_unique / array_flip
array_column($arr, "name")
sort / rsort / usort / uksort
๐ข Math
abs / round / ceil / floor
max / min / rand($min, $max)
pow(2, 8) // 256
sqrt(144) // 12
fmod(10, 3) // 1.0
intdiv(7, 2) // 3
number_format(1234.5, 2)
M_PI M_E PHP_INT_MAX
๐
Date & Time
date("Y-m-d") // "2024-03-15"
date("H:i:s") // "14:30:00"
time() // Unix timestamp
strtotime("next monday")
new DateTime("now")
$dt->format("Y-m-d H:i")
$dt->modify("+1 week")
date_diff($d1, $d2)->days
๐ HTTP & Headers
header("Location: /page.php");
header("Content-Type: application/json");
http_response_code(404);
setcookie("name","val",time()+3600);
$_SERVER["REQUEST_METHOD"]
$_SERVER["REQUEST_URI"]
$_SERVER["HTTP_HOST"]
$_SERVER["REMOTE_ADDR"]
๐ก๏ธ Security
htmlspecialchars($s, ENT_QUOTES, "UTF-8")
strip_tags($html)
filter_input(INPUT_POST, "k", FILTER_VALIDATE_EMAIL)
password_hash($p, PASSWORD_BCRYPT)
password_verify($p, $hash)
bin2hex(random_bytes(32)) // CSRF token
hash("sha256", $data)
๐๏ธ PDO Quick Ref
$pdo = new PDO($dsn, $u, $p, $opts);
$stmt = $pdo->prepare("SELECT...");
$stmt->execute([$val]);
$row = $stmt->fetch();
$rows = $stmt->fetchAll();
$pdo->lastInsertId();
$stmt->rowCount();
$pdo->beginTransaction();
$pdo->commit();
$pdo->rollBack();
๐๏ธ OOP Patterns
// Constructor promotion (PHP 8)
class User {
public function __construct(
private readonly int $id,
private string $name
) {}
}
// Enum (PHP 8.1)
enum Status: string {
case Active = "active";
case Inactive = "inactive";
}
โก PHP 8 Features
// Named arguments
array_slice(arr: $a, offset: 2);
// Nullsafe operator
$city = $user?->address?->city;
// Match expression
$r = match($n) {
1, 2 => "low",
3 => "mid",
default => "high",
};
// Union types
function f(int|string $v): void {}
๐ File Quick Ref
file_get_contents($path)
file_put_contents($p, $data)
file_put_contents($p, $d, FILE_APPEND)
file($p, FILE_IGNORE_NEW_LINES)
file_exists($p)
filesize($p) / filemtime($p)
pathinfo($p) // dir/base/ext
mkdir($p, 0755, true)
scandir($dir)
glob("*.php")
unlink($file)