PHP Basic Syntax

PHP has a small syntax and a large number of behaviours that only become visible when you look for them. A page of PHP looks like a page of almost anything: variables with a currency symbol, function calls with a name and a parenthesis pair, arrays written as if they were maps. What is not obvious from reading is that PHP is a dynamically typed language with a deliberately permissive conversion model, that the type of a variable can change during its life, and that the language gives you tools to remove that permissiveness one declaration at a time. By the end of this chapter you will be able to read a PHP file line by line, say what each construct does, predict how a value will be converted when two types meet, and write new code with the type declarations and the strictness setting that make the conversions predictable.

1. Where PHP code lives

PHP files are read as plain text until the interpreter finds an opening tag. Everything outside the tags is passed through to the output untouched, which is why a PHP file can hold HTML and PHP side by side.

<?php
// Everything between the tags is PHP.
$name = 'Ada';
?>
<p>Hello, <?= htmlspecialchars($name) ?>!</p>
<?php
// The parser resumes here.
?>

There are three tags worth knowing about.

  • <?php is the full opening tag and the only one you should use.
  • <?= is the short echo tag. It is always available, in every configuration, and it prints the expression that follows it. It is the only short tag that is guaranteed to work.
  • <? is the short opening tag. It requires the short_open_tag setting, which has been off by default since PHP 7, and relying on it is a portability bug waiting to happen.

The closing tag ?> is optional. You may leave it off entirely, and inside a pure PHP file it is better to leave it off, because a trailing newline after ?> is emitted as output. That stray byte is the classic cause of “headers already sent” errors in a framework. The one case where the closing tag is useful is when you want to end the PHP block and drop into raw HTML, as in the example above.

If a file begins with anything other than <?php or a byte order mark, that leading text is sent to the browser as output. A file that starts with a blank line is therefore not an empty file, it is a file that prints a newline.

2. Statements, semicolons and comments

Every statement ends with a semicolon. The exception is the last statement before a closing ?> in a block of pure PHP, where the semicolon may be omitted, a habit that is more confusing than it is convenient.

<?php
$total = 10;
$tax = $total * 0.2;
$grand = $total + $tax;

Control structures use braces around their bodies.

<?php
if ($grand > 12) {
    echo "over budget";
} elseif ($grand > 10) {
    echo "close";
} else {
    echo "fine";
}

Braces are optional for a single statement, but writing them anyway is the better habit, because a later edit that adds a second line does not silently change the meaning of the first.

There are three comment syntaxes.

<?php
// A line comment. Runs to the end of the line.
# Also a line comment. Same rule, different character.
/*
   A block comment.
   It spans lines, and it cannot be nested.
*/

A // or # comment ends at the end of the line or at a closing ?> tag, whichever comes first, and that second case is a genuine trap: a comment written as // note ?> swallows the rest of the line including the tag. A block comment ends at the first */, so it cannot be nested, and an unterminated one is a parse error that swallows the remainder of the file.

3. Variables and variable variables

A variable name is written with a currency symbol in front of it, followed by a letter or an underscore, then letters, digits and underscores. Names are case-sensitive: $name and $Name are two different variables.

<?php
$name = 'Ada';
$Name = 'Grace';
echo $name;  // Ada
echo $Name;  // Grace

A variable is created by the assignment. Reading an undefined variable is a warning, not an error, and it yields null.

<?php
echo $undefined;       // Warning: Undefined variable $undefined
var_dump($undefined);  // NULL

PHP also allows a variable whose name is stored in another variable. The curly-brace syntax is the modern form and should be preferred.

<?php
$key = 'total';
${$key} = 99;
echo $total;  // 99

// The older double-dollar form does the same thing.
$other = 'count';
$$other = 5;
echo $count;  // 5

This feature is occasionally the right tool for mapping names to values, but it is also a reliable source of bugs, because the name of the variable changes at runtime and no static tool can follow it. Use it sparingly.

Variables in PHP carry a reference count internally, and assigning one variable to another does not copy the value: both names refer to the same value, and changing it through one name is visible through the other. The array chapter explains this in detail, because the same rule explains why foreach needs an explicit reference to modify the loop variable in place.

4. Strings in four flavours

PHP has four ways to write a string, and they differ in how much processing they apply.

Single quotes are literal. Only \' and \\ are escapes; nothing else is interpreted, and no variable is substituted.

<?php
$name = 'Ada';
echo 'Hello $name\n';   // Hello $name\n

Double quotes are interpolated. Variables, escape sequences and a small amount of formatting are processed.

<?php
$name = 'Ada';
$items = ['apples' => 3];

echo "Hello $name\n";
echo "You have {$items['apples']} apples\n";

Interpolation accepts a bare name, a name followed by a one-dimensional array index such as $items[0], or a braced expression such as {$items['apples']}. The braced form is the one to reach for when the expression is anything other than trivial, because it removes all ambiguity about where the name ends.

The escape sequences recognised inside double quotes are \n, \r, \t, \v, \e, \f, \\, \$, \", \xNN for a single byte in hexadecimal, and \u{...} for a Unicode code point.

Heredoc behaves like a double-quoted string but spans multiple lines and is not written in quotes.

<?php
$name = 'Ada';
$message = <<<TEXT
    Hello $name,
    welcome aboard.
    TEXT;
echo $message;

Nowdoc is the non-interpolating counterpart, and it is written with single quotes around the label.

<?php
$template = <<<'TEXT'
    Hello $name,
    this stays exactly as written.
    TEXT;
echo $template;

Since PHP 7.3 the closing label may be indented, and the indentation of the closing label is stripped from every line of the body. The label must be followed by a semicolon, and it may not be indented less than the body.

Nowdoc is the right tool for templates and configuration snippets, because it guarantees that a dollar sign in the text stays a dollar sign. It is the single most useful habit for writing code that other people will also have to read.

A PHP string is a byte sequence, not a sequence of characters. Functions that deal with characters rather than bytes live in the mb_ family, such as mb_strlen and mb_substr, and they are the right choice whenever the text may contain anything outside ASCII.

5. Control flow

The conditional forms are the usual ones.

<?php
$score = 85;

if ($score >= 90) {
    echo "excellent";
} elseif ($score >= 70) {
    echo "good";
} else {
    echo "needs work";
}

PHP also has switch and match, and they are not interchangeable. switch uses loose comparison and falls through from one case to the next unless a break says otherwise. match is the PHP 8 expression: it compares strictly, has no fall-through, and produces a value.

<?php
$status = 'ok';

$message = match ($status) {
    'ok'    => 'fine',
    'error' => 'failed',
    default => 'unknown',
};

echo $message;   // fine

A match with no matching arm and no default throws an UnhandledMatchError, which is a feature: a switch that silently does nothing on an unexpected value is a bug waiting to happen.

<?php
$grade = match (true) {
    $score >= 90 => 'A',
    $score >= 70 => 'B',
    default      => 'C',
};

The three loop forms cover the usual cases.

<?php
for ($i = 0; $i < 3; $i++) {
    echo $i;
}

$count = 0;
while ($count < 3) {
    echo $count;
    $count++;
}

$count = 0;
do {
    echo $count;
    $count++;
} while ($count < 3);

The do loop runs its body at least once, which is what you want when the condition depends on something the body does. foreach is the loop you will use most, and the array chapter covers it in detail. break exits a loop and continue skips to the next iteration, and both accept a level, so break 2 leaves two nested loops at once.

6. Data types and how to inspect them

PHP has eight types that matter in practice.

TypeLiteral examplesNotes
int42, -7, 0x1A, 0b1010, 0o17Integer arithmetic wraps around on overflow
float3.14, 1.0e3, .5Double precision, follows IEEE 754
string'text', "text", heredocA byte string; valid UTF-8 is a convention, not a guarantee
booltrue, falseOnly false, 0, 0.0, "", "0", [] and null are falsy
array[1, 2], ['k' => 'v']An ordered map; the type used for lists, dictionaries and sets
objectnew stdClassAny instance of a class
nullnullThe value of an uninitialised variable, unset variable, or a failed match
callable'strlen', [$obj, 'method']A string, an array pair, a closure or an invokable object

Two built-in functions answer the questions you will actually ask.

<?php
$price = 19.99;

echo gettype($price);       // double
echo get_debug_type($price); // float

gettype is the older function and it reports double for floats and integer for integers. get_debug_type, added in PHP 8, reports the names used in the type system itself: float, int, bool, null, array, object, string, callable, resource, never, mixed. Prefer get_debug_type in new code.

var_dump is the debugging tool that shows both the value and the type.

<?php
var_dump(19.99, "19.99", true, null, [1, 2]);
float(19.99)
string(5) "19.99"
bool(true)
NULL
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

There is a family of type predicates as well: is_int, is_float, is_string, is_bool, is_array, is_object, is_null, is_callable, is_numeric, is_iterable. is_numeric is the one to reach for when you are validating user input, because it is true for integers, floats and numeric strings, and false for strings such as "12abc".

7. Type declarations and strict types

Function parameters and return values can be declared, and in PHP 8 the set of declarations is rich.

<?php
function greet(string $name, int $times = 1): string
{
    return str_repeat("Hello $name. ", $times);
}

The declaration types are int, float, string, bool, array, object, callable, iterable, mixed, void, never, null, false, true, the nullable shorthand ?Type, union types such as int|string, and intersection types such as Countable&ArrayAccess.

By default, PHP converts a value to the declared type when it can. Passing "42" to a parameter declared int gives you the integer 42.

<?php
function add(int $a, int $b): int
{
    return $a + $b;
}

echo add("2", "3");   // 5, the strings became integers
echo add(2.5, 1);    // 3, the float became an integer

The second call also emits a deprecation notice, because PHP 8.1 deprecated the implicit conversion of a float that loses precision. The value is still 3, but the notice is the language telling you that the conversion was lossy and should have been written down.

The mode where values are converted rather than rejected is called weak typing, and it is the default. It is also the source of a long list of subtle bugs, because the conversion rules for arrays, objects and non-numeric strings are not intuitive.

The fix is the declare statement, which must be the first statement in the file.

<?php
declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

add("2", "3");   // TypeError: Argument #1 ($a) must be of type int, string given

One detail is worth remembering because it catches everybody once: strictness is decided by the file that makes the call, not by the file that declares the function. If add is declared in a weak file but called from a strict file, the call is strict. If it is declared in a strict file but called from a weak file, the call is weak.

Turning strict types on is close to free. The cost is that some legacy calls will start throwing TypeError, and each of those is a place where the program was previously accepting a value it should not have accepted.

8. Operators and precedence

PHP’s operators are grouped by precedence. The table below lists the ones you meet daily, from the tightest binding to the loosest.

PrecedenceOperatorsNotes
1clone, new
2<strong>Exponentiation, right associative: 2</strong> 3 ** 2 is 512
3++, --, ~, (int), @Prefix and postfix increment, bitwise not, casts, error suppression
4instanceof
5!Logical not
6*, /, %Integer division only when both operands are integers
7+, -
8<<, >>Bitwise shifts
9.String concatenation, binds looser than + and -
10<, <=, >, >=Comparison
11==, !=, ===, !==, <=>Loose and strict comparison, spaceship
12&, ^, |Bitwise and, xor, or
13&&, ||Logical and, or
14??Null coalescing
15? :Ternary
16=, +=, -=, *=, /=, .=, ??=, **=Assignment, right associative
17and, xor, orLowest precedence, used for readable conditionals

Two rows deserve emphasis. The concatenation operator binds looser than addition, so "Total: " . 1 + 2 produces Total: 3 rather than a numeric result. And the word operators and, or and xor bind looser than every symbol operator, which is why the manual recommends the symbolic forms.

<?php
// These two lines mean different things.
$result = $a and $b;   // assigns $a, then evaluates $a and $b
$result = $a && $b;    // evaluates $a && $b, then assigns

The comparison operators come in two families, and the difference matters.

<?php
var_dump(0 == "0");    // true
var_dump(0 === "0");   // false

The loose operators compare values after converting them to a common type. The strict operators compare both the type and the value. The strict forms are almost always the ones you want, because they fail loudly instead of quietly.

One PHP 8 change is worth knowing because it invalidates advice from older tutorials: when a number is compared with a string that does not look like a number, the number is converted to a string rather than the other way round. So "abc" == 0 was true in PHP 7 and is false in PHP 8.

<?php
var_dump("abc" == 0);     // false
var_dump("1abc" == 1);    // false
var_dump("1" == 1);       // true, "1" is a numeric string

The spaceship operator returns -1, 0 or 1 and is the standard way to sort with a custom rule.

<?php
$a <=> $b;   // -1 if a is smaller, 0 if equal, 1 if larger

Two operators exist to make intent explicit where the alternative is a nested conditional.

<?php
$name = $input['name'] ?? 'anonymous';   // null coalescing: falls back on null and on undefined
$total = $price ?? 0;
$total ??= 10;                          // assigns only if $total is null or undefined

The null coalescing operator reads an array key without emitting a warning when the key is missing, which makes it the cleanest way to express a default.

9. Type juggling and explicit casts

Because the language converts values, it is worth knowing what the conversions do.

<?php
var_dump((int) "12abc");   // int(12)
var_dump((int) "abc");     // int(0)
var_dump((int) "1.9");     // int(1)
var_dump((float) "1.5e3"); // float(1500)
var_dump((string) 42);     // string(2) "42"
var_dump((bool) "0");      // bool(false)
var_dump((bool) "0.0");    // bool(true)
var_dump((array) "text");  // array(1) { [0]=> string(4) "text" }

The rules that catch people are the string ones. "0" is falsy, but "0.0" and " " are truthy. An empty array is falsy, and an array that merely holds a 0 is truthy, because the array itself is not empty. A string that starts with a number is truthy even if the rest of it is not numeric.

Floating point is subject to the usual binary rounding problem.

<?php
var_dump(0.1 + 0.2 === 0.3);   // false
echo 0.1 + 0.2;                // 0.3

The comparison is false because the sum is not exactly the double nearest to 0.3, even though var_dump and echo print it as 0.3 thanks to the shortest round-trip representation. For money, use integers of minor units, or a decimal library.

When you want a conversion to be visible in the code, write the cast. The idiomatic cast to an integer is (int), and the modern explicit forms are intval, floatval, strval and boolval.

10. Constants

A constant is a name bound to a value that cannot change. It is defined with const at compile time, or with define() at runtime.

<?php
const APP_NAME = 'Ledger';
define('MAX_RETRIES', 3);

echo APP_NAME;      // Ledger
echo MAX_RETRIES;   // 3

The two differ in three ways that matter in practice.

  • const is resolved at compile time, so it can be used in a constant expression, in a class constant, and in an array size. define() is a function call that happens at runtime.
  • define() can be called conditionally and can be given a third argument to make the name case-insensitive. const cannot.
  • const cannot be used inside a function body at all; it is a parse error there. Use define() when the name has to be created at runtime.
<?php
function register(string $name, int $limit): void
{
    define($name, $limit);   // the only option inside a function
}

Constants are case-sensitive by default, and since PHP 7.2 that is true of define() as well. Passing true as the third argument makes a name case-insensitive, which is a legacy habit rather than a recommendation.

<?php
define('APP_ENV', 'production');
var_dump(defined('APP_ENV'));   // bool(true)
var_dump(defined('app_env'));   // bool(false)

A constant can also hold an array.

<?php
const FEATURES = ['export', 'import'];
echo FEATURES[0];   // export

11. Scope

PHP has four visibility levels for variables.

Global scope is the top level of a script. A variable created there is not visible inside a function.

<?php
$counter = 1;

function bump(): void
{
    echo $counter;   // Warning: Undefined variable $counter
}

The global keyword imports a global variable into the local scope of a function.

<?php
$counter = 1;

function bump(): void
{
    global $counter;
    $counter++;
}

bump();
echo $counter;   // 2

Function scope is the body of a function. Every call gets a fresh copy of the local variables, and they disappear when the function returns.

Static scope keeps a local variable alive between calls of the same function. It is initialised once, the first time the function runs.

<?php
function counter(): int
{
    static $n = 0;
    return ++$n;
}

echo counter();   // 1
echo counter();   // 2
echo counter();   // 3

This is the standard way to write a memoised helper or a lazily built lookup table.

<?php
function slugMap(): array
{
    static $map = null;
    if ($map === null) {
        $map = buildExpensiveMap();
    }
    return $map;
}

A variable declared static at the top level of a file behaves like a class constant for the purposes of the request: it exists once per request and cannot be redefined.

12. Output

PHP has four ways to write to the output buffer, and they differ in what they return and how they format.

echo prints one or more arguments and returns nothing. It is the cheapest of the four.

<?php
echo "Hello";
echo "Hello", " ", "world";

print takes exactly one argument and returns 1, so it can be used in an expression. It is marginally slower than echo and used far less often.

<?php
$result = print "Hello";   // $result is 1

printf formats according to a format string.

<?php
printf("Order %s: %d items at %.2f each\n", 'A-100', 3, 19.99);
// Order A-100: 3 items at 19.99 each

The most common specifiers are %s for a string, %d for an integer, %f for a float, %.2f for a float with two decimals, %b for binary, %x and %o for hexadecimal and octal, and %e for scientific notation.

var_dump is not for output, it is for inspection. It prints the type and the value of every argument, and it is the fastest way to see what a variable actually contains.

<?php
var_dump($price, $items);

There is also print_r, which is friendlier to read than var_dump and returns the value rather than printing it, and var_export, which produces valid PHP source code for a value.

<?php
print_r($items);
$code = var_export($items, true);

For anything a user will see, remember that echo does not escape. htmlspecialchars is the function that turns a value into safe HTML.

<?php
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

13. Including other files

Four constructs load another PHP file: include, include_once, require and require_once.

<?php
require 'config.php';
include 'templates/header.php';
require_once 'vendor/autoload.php';

The difference between the two families is what happens when the file cannot be found.

  • require stops the script with a fatal error.
  • include emits a warning and continues.

include_once and require_once skip the file if it has already been included in the current request, tracked by the resolved path. They are the right choice for a bootstrap file or an autoloader, and the wrong choice for a file that genuinely needs to run twice.

The path is resolved against the include path and then the calling script’s directory, and it may be absolute or relative.

<?php
require __DIR__ . '/lib/helpers.php';

__DIR__ gives the directory of the current file and is the correct anchor for any path you build yourself, because it does not depend on the working directory or on where the script was invoked from.

14. Superglobals

PHP makes a small set of arrays available in every scope. They do not need global and cannot be overwritten.

SuperglobalContains
$_SERVERServer and environment information, including the request method and the request URI
$_GETQuery string parameters
$_POSTForm body fields submitted with POST
$_REQUESTThe combined result of $_GET, $_POST and $_COOKIE
$_COOKIEClient cookies
$_FILESUploaded file information, one entry per file in $_FILES
$_SESSIONSession variables, once a session has been started
$_ENVEnvironment variables available to the process
$_SERVER['argv']Command line arguments, when running from the command line

Every one of them is user-controlled data unless you have established otherwise. $_GET, $_POST, $_COOKIE and $_SERVER in particular must be validated before use, and the type of a query parameter is always a string.

<?php
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;

The $_SERVER array is worth exploring with phpinfo(), which prints every environment variable, every loaded extension and the whole configuration table for the current request. It is a debugging tool; on a public server it leaks information, so it is removed or restricted in production.

15. Common mistakes

MistakeWhat actually happensCorrection
Using <? to open a scriptThe tag is disabled by default since PHP 7, so the code is printed as textUse <?php
Leaving a newline after a closing ?>The newline is sent as output, which breaks header callsOmit the closing tag in pure PHP files
Putting a comment after ?> on the same lineThe // comment swallows the tagKeep the tag on its own line
Relying on implicit conversion"abc" becomes 0, and "12abc" becomes 12Declare types and enable strict_types
Comparing with =="0" and 0 and false are all equalUse === for type-sensitive comparisons
Using and inside an assignment$a = $b and $c assigns $bUse &&
Expecting const inside a functionIt is a parse errorUse define()
Assuming static variables reset each callThey keep their value between callsUse a local variable for a fresh counter
Echoing unescaped user inputThis is how HTML injection happensWrap the value in htmlspecialchars
Assuming a strict file makes its functions strictStrictness comes from the calling fileSet declare(strict_types=1) in the caller

With the syntax in place, the next chapter takes the single most important data structure in the language and shows you how to work with it: how arrays are keyed, how to traverse them, how to add and remove elements, how to search and sort, and how the reference semantics affect every one of those operations.

phpfundamentals

Approach:

The subject of this chapter is syntax, but the skill being taught is prediction. PHP will convert a value for you if you let it, so the practical question for every line of code is not “what does this do” but “what type will this value have when it reaches the next line”. The answer is found in three places, and the chapter builds them in order: the declaration system, which states the intended type of every parameter and return value; the strictness setting, which decides whether a mismatched argument is converted or rejected; and the conversion rules themselves, which decide what happens to a value that no declaration covers. Reading code with those three things in mind turns a page of apparently ordinary statements into a sequence of type facts.

Steps:

  1. Start with the physical structure of a file: the opening tag, the rule that everything outside the tags is literal output, the fact that a trailing newline after the closing tag is itself output, and the reason the closing tag is best omitted in a pure PHP file.
  2. Establish the statement forms: semicolons, braces, and the three comment syntaxes, including the two ways a comment can end unexpectedly and the fact that block comments cannot be nested.
  3. Fix the variable model: the currency symbol, case sensitivity, the rule that a variable is created by assignment, that reading an undefined variable warns and yields null, and that variable names can themselves be stored in variables.
  4. Compare the four string forms side by side, because the differences between single quotes, double quotes, heredoc and nowdoc explain most string bugs in PHP. Single quotes are literal, double quotes interpolate, heredoc interpolates across lines, nowdoc does not interpolate at all and is therefore the right tool for templates.
  5. Cover the control flow forms and the one distinction that matters most: switch compares loosely and falls through, while match compares strictly, returns a value and throws when nothing matches.
  6. Enumerate the types and the tools that report them, so that a value’s type can be checked rather than guessed: gettype, get_debug_type, var_dump, and the is_ family.
  7. Move to the declaration system: parameter types, return types, nullable and union and intersection types, and the weak-by-default conversion model. Then introduce declare(strict_types=1) and the rule that the calling file decides strictness, not the declaring file.
  8. Work through the operator table from tightest to loosest binding, paying attention to the two rows that cause surprises: concatenation binds looser than addition, and the word operators and, or and xor bind looser than every symbol operator. Note also the PHP 8 change to the comparison of a number with a non-numeric string.
  9. Distinguish the loose comparison operators from the strict ones, and treat the spaceship operator as the default way to express a custom ordering.
  10. Catalogue the conversions that happen implicitly and the explicit casts that happen on purpose, including the string rules that catch people: "0" is falsy but "0.0" is truthy, and an array holding a single 0 is truthy.
  11. Finish with the parts of the language that surround expressions: constants and the difference between const and define(), the four scopes including the persistent local variable declared static, the four output functions and what each returns, the difference between include and require, the correct way to build a file path with __DIR__, and the superglobals that arrive as user input.

Answer:

After this chapter, a PHP file can be read as a sequence of type facts rather than as a sequence of symbols.

  • Every statement is delimited by a semicolon, every block is delimited by braces, and every comment is either a line comment that ends at the newline or a block comment that ends at the first */.
  • Every value has a type that can be inspected with get_debug_type and var_dump, and every parameter and return value can carry a declaration that states the type the code intends.
  • The mode of the language is weak typing unless the calling file declares strict_types=1, and the calling file is what decides, so a strict caller always gets an error rather than a silent conversion.
  • Every operator has a fixed precedence, the two that matter most being that concatenation binds looser than addition and that the word operators bind looser than everything else, and every comparison has a strict form that also compares the type.
  • Every branch is either a loose switch or a strict match, and a match with no matching arm fails loudly rather than silently doing nothing.
  • Every constant is created either at compile time with const or at runtime with define(), and const is a parse error inside a function body.
  • Every variable lives in one of four scopes, and the static keyword is the way to keep a local value alive between calls of the same function.
  • Every piece of output goes through echo, print, printf or var_dump, and every value that reaches a browser is escaped with htmlspecialchars.
  • Every file that is loaded is loaded with require or include, with the _once variants used only where loading twice is genuinely wrong, and every path built by hand is anchored with __DIR__.

That is the whole of the syntax layer, and it is enough to read the array, function and object chapters that follow without guessing.

Found an issue with this content?

Tell us what could be improved.