PHP Cheatsheet
Basics
Use this PHP reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
File Shape
<?php declare(strict_types=1); echo 'Hello' . PHP_EOL;
Pure PHP files usually omit the closing ?> tag. Put declare(strict_types=1); near the top when you want stricter function parameter and return checks for calls made from that file.
Variables and Scalars
$name = 'Ada'; $count = 3; $price = 19.99; $active = true; $missing = null;
Variables start with $. Scalar types: int, float, string, bool, plus null. Type checks: is_int, is_float, is_string, is_bool, is_array, is_object, is_null.
Constants
const MAX_RETRIES = 3; // compile-time, also valid in classes define('APP_VERSION', '2.1.0'); // runtime PHP_EOL; PHP_INT_MAX; PHP_FLOAT_EPSILON; M_PI;
Constants have no $ prefix and cannot be reassigned. Prefer const unless the name or value is computed at runtime.
Operators
$a + $b; $a - $b; $a * $b; $a / $b; $a % $b; $a ** $b; intdiv(7, 2); // 3, integer division $text = 'Hello ' . $name; $count += 1; $count++; $count--;
Use . for string concatenation. Use + for numeric addition. / always produces a float unless both operands divide evenly.
Casting and Conversion
(int) '42'; // 42 (float) '3.5'; // 3.5 (string) 99; // '99' (bool) ''; // false (array) $obj; intval('08', 10); // 8, explicit base '5' + 2; // 7, numeric strings coerce in math 'abc' <=> 'abd'; // strings compare byte-wise
(int) 'abc' is 0, but since PHP 8 using a fully non-numeric string in arithmetic throws TypeError, and a leading-numeric string like '5 apples' uses the leading number with a warning. Validate with is_numeric before trusting numeric input.
Comparison
$a === $b; // same value and type $a !== $b; $a == $b; // loose comparison, avoid by default $a <=> $b; // -1, 0, or 1
Prefer === and !==. Loose comparison performs type juggling and can surprise beginners.
Truthiness
Falsy values include false, 0, 0.0, '', '0', [], and null. Non-empty strings other than '0' are truthy.
Output and Debugging
echo $name; // basic output echo $a, ' and ', $b; // multiple values print_r($array); // readable structure var_dump($value); // type + value, best for debugging error_log(print_r($data, true)); // structure into the error log
var_dump shows exact types (string(3) "Ada"), which makes type-juggling bugs visible. Never leave var_dump in production responses.