PHP
Basics
<?php ... ?>—PHP opening/closing tags
$var = "value";—Variable (always $ prefix)
echo "text";—Output to browser
print_r($var);—Print readable info
var_dump($var);—Detailed type + value
define("CONST", val);—Define constant
const NAME = val;—Class constant
isset($var)—Check if set and not null
empty($var)—Check if empty/falsy
Data Types & Casting
string—Text type
int / float—Number types
bool—true or false
array—Array type
null—No value
gettype($var)—Get type name
(int) $var—Cast to integer
(string) $var—Cast to string
intval($str)—Parse integer
is_array($var)—Type check
Strings
"Hello $name"—Double-quote interpolation
'literal string'—No interpolation
strlen($s)—String length
strpos($s, "sub")—Find position
substr($s, start, len)—Substring
str_replace(old, new, $s)—Replace
explode(",", $s)—Split to array
implode(",", $arr)—Join array to string
trim($s)—Remove whitespace
strtolower($s) / strtoupper()—Case conversion
Arrays
$arr = [1, 2, 3];—Indexed array
$arr = ["k" => "v"];—Associative array
count($arr)—Array length
array_push($arr, $val)—Add to end
array_pop($arr)—Remove from end
array_merge($a, $b)—Merge arrays
array_map(fn, $arr)—Transform each element
array_filter($arr, fn)—Filter elements
in_array($val, $arr)—Check if value exists
array_keys($arr)—Get all keys
sort($arr) / asort($arr)—Sort by value
foreach ($arr as $k => $v)—Loop over array
Functions & Classes
function fn($a, $b) { }—Define function
fn($a, $b = 5)—Default parameter
function fn(int $a): string—Type hints
fn(...$args)—Variadic arguments
$fn = fn($x) => $x * 2;—Arrow function
class MyClass { }—Define class
new MyClass()—Create instance
$this->prop—Instance property
public / private / protected—Visibility
extends / implements—Inheritance / interface
Control Flow
if ($cond) { } else { }—If-else
switch ($val) { case: }—Switch statement
match ($val) { pat => result }—Match expression (8.0+)
for ($i=0; $i<$n; $i++)—For loop
foreach ($arr as $v)—Foreach loop
while ($cond) { }—While loop
$a ?? $b—Null coalescing
$a ?. method()—Nullsafe operator (8.0+)
Error Handling & I/O
try { } catch (Exception $e) { }—Try-catch
throw new Exception(msg)—Throw exception
finally { }—Always executes
file_get_contents($path)—Read file to string
file_put_contents($path, $d)—Write string to file
json_encode($data)—Convert to JSON
json_decode($json, true)—Parse JSON to array
allprintabledoc.com