Tags and statements
<?php
declare(strict_types=1); // optional: strict type checks for function arguments
// single-line comment
# also a single-line comment
/* multi-line comment */
echo "Hello World"; // every statement ends with ;A file that only contains PHP should not have a closing ?> tag – this avoids accidental whitespace output.
Variables and types
Variables start with $ and are case-sensitive. PHP decides the type at runtime.
| Type | Example |
|---|---|
| string | $name = "Bugfish"; |
| int | $age = 42; |
| float | $price = 9.99; |
| bool | $active = true; |
| array | $list = [1, 2, 3]; |
| null | $x = null; |
| object | $d = new DateTime(); |
$name = "World";
echo "Hello $name"; // double quotes: variables are inserted
echo 'Hello $name'; // single quotes: printed literally
echo "Hello {$user['name']}"; // braces for arrays/objectsConstants
const APP_NAME = "Bugfish"; // compile time, also inside classes
define('VERSION', '1.0'); // runtime
echo PHP_VERSION, PHP_EOL; // built-in constantsOutput commands
| Command | Use |
|---|---|
echo $a, $b; | Print one or more values (fastest, most common) |
print $a; | Print one value, returns 1 |
printf("%s is %d", $n, $a); | Formatted output |
print_r($array); | Readable view of arrays/objects |
var_dump($x); | Type and value – best for debugging |
var_export($x, true); | Value as valid PHP code (as string) |
Checking values
| Function | Returns true when |
|---|---|
isset($x) | variable exists and is not null |
empty($x) | not set, or "", 0, "0", 0.0, [], null, false |
is_null($x) | value is null |
is_string(), is_int(), is_float(), is_bool(), is_array(), is_numeric() | matching type |
gettype($x) / get_debug_type($x) | returns type name (latter PHP 8+) |
unset($x) removes a variable or an array element.
$user = $_GET['user'] ?? 'guest'; // null coalescing: default if not set/null
$config['debug'] ??= false; // assign only if not setOperators
| Operator | Meaning | ||
|---|---|---|---|
+ - * / % ** | arithmetic (** = power) | ||
. / .= | string concatenation / append | ||
== | equal after type juggling ("1" == 1 is true) | ||
=== | equal and same type – prefer this | ||
!= / !== | not equal / not identical | ||
<=> | spaceship: -1, 0 or 1 (for sorting) | ||
| `&& \ | \ | !` | logical and, or, not |
? : / ?: | ternary / short ternary | ||
?-> | nullsafe call (PHP 8): $user?->getName() |
Put together with AI as a quick reference I keep for my own work. Entries like this are usually not reviewed in detail by a person.