Variables & Types
$name = valueVariable assignment — $ prefix required$x = 42Integer$x = 3.14Float$x = "hello"String (double quotes allow interpolation)$x = 'hello'String (single quotes — literal, no interpolation)$x = true / falseBoolean$x = nullNull — absence of a value$x = [1, 2, 3]Array literalgettype($x)Returns type as string: "integer", "double", "string", "boolean", "array", "NULL"is_int($x) / is_float($x) / is_string($x)Type-check functionsis_null($x) / is_array($x) / is_bool($x)More type-check functionsisset($x)True if variable exists and is not nullempty($x)True if falsy: 0, "", "0", [], null, false(int) $x / (string) $x / (float) $xCast to typeintval($x) / strval($x) / floatval($x)Convert to type via functionconst MAX = 100Global constant (no $ prefix)define("MAX", 100)Runtime constant definitionStrings
"Hello, $name!"Variable interpolation in double-quoted strings"Hello, {$obj->name}!"Expression interpolation with curly braces$a . $bString concatenation with dot operatorstrlen($s)Number of bytes (use mb_strlen() for multibyte)strtolower($s) / strtoupper($s)Change caseucfirst($s) / ucwords($s)Capitalise first letter / each wordtrim($s) / ltrim($s) / rtrim($s)Strip whitespace from both / left / rightstr_contains($s, "sub")True if substring found (PHP 8+)str_starts_with($s, "pre") / str_ends_with($s, "suf")Check prefix/suffix (PHP 8+)strpos($s, "sub")First position of substring (false if not found)substr($s, 2, 5)Extract substring: start offset, lengthstr_replace("a", "b", $s)Replace all occurrencesstr_ireplace("a", "b", $s)Case-insensitive replaceexplode(",", $s)Split string into array on delimiterimplode(", ", $arr)Join array into string with gluesprintf("Hello %s, you are %d", $name, $age)Format stringnumber_format(1234567.891, 2)Format number: "1,234,567.89"htmlspecialchars($s)Escape HTML entities — use before outputting user inputnl2br($s)Insert before newlines
str_pad($s, 10, "0", STR_PAD_LEFT)Pad string to lengthstr_repeat("ab", 3)Repeat string N times: "ababab"preg_match("/pattern/", $s)Test regex match — returns 1 or 0preg_replace("/pattern/", "replace", $s)Regex replacepreg_split("/[\s,]+/", $s)Split by regexArrays
$arr = [1, 2, 3]Indexed array$map = ["key" => "val"]Associative array (key => value)$arr[] = 4Append to arraycount($arr)Number of elementsarray_push($arr, 4, 5)Push one or more values onto endarray_pop($arr)Remove and return last elementarray_shift($arr)Remove and return first elementarray_unshift($arr, 0)Prepend element(s) to startin_array("val", $arr)True if value exists in arrayarray_key_exists("key", $map)True if key existsarray_keys($map)Array of all keysarray_values($arr)Re-indexed array of all valuesarray_merge($a, $b)Merge arrays (numeric keys re-indexed)array_slice($arr, 1, 3)Extract portion: start offset, lengtharray_splice($arr, 1, 2, ["x"])Remove and/or insert elements (mutates)array_map(fn($x) => $x * 2, $arr)Transform each elementarray_filter($arr, fn($x) => $x > 2)Filter elements by callbackarray_reduce($arr, fn($carry, $x) => $carry + $x, 0)Reduce to single valuesort($arr) / rsort($arr)Sort ascending / descending (mutates, re-indexes)asort($arr) / arsort($arr)Sort preserving keysksort($map) / krsort($map)Sort by keyusort($arr, fn($a, $b) => $a - $b)Sort with custom comparatorarray_unique($arr)Remove duplicate valuesarray_flip($arr)Swap keys and valuesarray_reverse($arr)Reverse orderarray_chunk($arr, 3)Split into chunks of size Narray_combine($keys, $vals)Create associative array from two arraysarray_search("val", $arr)Key of first matching value (false if not found)compact("name", "age")Create array from variable namesextract($map)Import array keys as variables into scopeControl Flow
if ($x > 0) { } elseif ($x < 0) { } else { }Conditional branches$x > 0 ? "pos" : "neg"Ternary operator$x ?: "default"Elvis operator — returns $x if truthy, else "default"$x ?? "default"Null coalescing — returns $x if set and not null$x ??= "default"Null coalescing assignmentmatch ($x) { 1 => "one", 2 => "two", default => "other" }match expression — strict comparison, no fallthroughswitch ($x) { case 1: break; default: }switch — loose comparison, falls through without breakfor ($i = 0; $i < 10; $i++) { }C-style for loopforeach ($arr as $val) { }Iterate array valuesforeach ($map as $key => $val) { }Iterate key => value pairswhile ($x > 0) { }Loop while condition is truedo { } while ($x > 0)Execute at least once, then check conditionbreak / break 2Exit loop (break 2 exits two levels)continue / continue 2Skip to next iterationreturn $valueReturn value from functionFunctions
function add(int $a, int $b): int { return $a + $b; }Named function with type hintsfunction greet(string $name = "World"): string { }Default parameter valuefunction sum(int ...$nums): int { return array_sum($nums); }Variadic — collects extra args as arrayfunction log(string $msg, bool $verbose = false): void { }void return typefn($x) => $x * 2Arrow function (short closure, captures outer scope by value)function($x) use ($multiplier) { return $x * $multiplier; }Anonymous function capturing outer variableadd(b: 2, a: 1)Named arguments (PHP 8+) — order independentfunction foo(?string $s): ?int { }Nullable type — allows null in addition to declared typefunction foo(int|string $x): void { }Union types (PHP 8+)function foo(mixed $x): never { }mixed accepts any type; never means function always throws/exitsfunction &getRef(): string { return $this->name; }Return by referencefunction foo(array &$arr): void { }Parameter passed by referenceClasses & OOP
class Dog extends Animal implements Runnable { }Class declaration with inheritance and interfacepublic function __construct(private string $name) { }Constructor property promotion (PHP 8+)$dog = new Dog("Rex")Instantiate object$dog->name / $dog->bark()Access property / call methodDog::MAX_AGE / Dog::create()Access static property / static method$this->nameCurrent instance propertyparent::__construct($args)Call parent constructorself::$count / static::$countself:: resolves at definition time; static:: resolves at runtime (late static binding)public / protected / privateVisibility: public=anywhere, protected=class+subclasses, private=class onlyreadonly string $nameProperty can only be written once in constructorabstract class Shape { abstract public function area(): float; }Abstract class — cannot be instantiatedinterface Drawable { public function draw(): void; }Interface — defines contract, no implementationtrait Loggable { public function log(): void { } }Trait — reusable method bundleuse Loggable;Include trait in a classenum Status { case Active; case Inactive; }Backed enum (PHP 8.1+)enum Color: string { case Red = "red"; case Blue = "blue"; }String-backed enumStatus::Active / Color::Red->valueAccess enum case / backed value$obj instanceof ClassNameCheck if object is instance of classclone $objShallow copy of objectpublic function __toString(): string { }Magic method — called when object cast to stringpublic function __get($name) / __set($name, $val)Magic property accessError Handling
try { } catch (Exception $e) { } finally { }Try/catch/finally — finally always runscatch (TypeError | ValueError $e) { }Catch multiple exception types (PHP 8+)throw new Exception("message")Throw an exceptionthrow new InvalidArgumentException("bad arg")Specific exception types$e->getMessage() / $e->getCode() / $e->getTrace()Exception methodsclass AppException extends RuntimeException { }Custom exception classset_exception_handler(fn($e) => logger($e->getMessage()))Global uncaught exception handlererror_reporting(E_ALL)Set which errors are reportedtrigger_error("msg", E_USER_WARNING)Trigger a user-level errorCommon Built-ins
date("Y-m-d H:i:s")Current date/time formattedtime()Current Unix timestampstrtotime("next Monday")Parse date string to timestampjson_encode($data)Encode to JSON stringjson_decode($json, true)Decode JSON — true returns associative arrayvar_dump($x)Print type and value — for debuggingprint_r($arr)Human-readable array/object printvar_export($x, true)Return parseable PHP representationrand(1, 100)Random integer between min and maxarray_rand($arr)Random key from arrayshuffle($arr)Shuffle array in placeround($x, 2) / ceil($x) / floor($x)Round / round up / round downabs($x) / max($a, $b) / min($a, $b)Absolute value / max / minfile_get_contents($path)Read file into stringfile_put_contents($path, $data)Write string to filefile_exists($path)Check if file or directory existsis_file($path) / is_dir($path)Check if path is a file / directoryunlink($path)Delete a fileglob("*.php")Find files matching patternheader("Location: /url")Send HTTP header (must be before output)http_response_code(404)Set HTTP response status codeob_start() / ob_get_clean()Output buffering — capture output as stringclass_exists("ClassName")Check if class is definedmethod_exists($obj, "name")Check if method exists on objectfunction_exists("name")Check if function is definedcall_user_func($callable, ...$args)Call callable dynamically