Explain it simply
Syntax in plain words
A PHP file is a list of instructions. Each one is called a statement, and the semicolon (`;`) is its full stop. PHP reads from top to bottom and ignores spaces, indentation and blank lines, which exist for humans only.
Think of a recipe in which every step ends with a full stop, and notes in the margin (comments) are for the cook, not the machine. There are few rules, but they are strict: forget one `;` and PHP refuses to run the whole file.
Problem → Why → Solution
The problem: one missing semicolon and the whole script refuses to run
In the script below the `;` at the end of the second line is missing. Running it gives `Parse error: syntax error, unexpected token "echo"`. The surprise is that the error points at line 3 (`echo`) rather than at line 2, where the real mistake is.
The reason is that after `"Aye Aye"` PHP cannot tell whether the statement continues, so it only notices the problem when it meets `echo`. A parse error also stops everything: PHP compiles the whole file before running it, so even lines above the mistake print nothing.
<?php
$name = "Aye Aye"
echo "Hello, $name";Why the error is not on the line you expect
PHP reports a problem at the place where it meets a token it did not expect, so look at the line above the reported one first. If it is not there, check that quotes and brackets are balanced.
Core concept: statements, expressions and case sensitivity
A script is a row of statements. An expression is anything that produces a value, such as `5 + 3`, `$a` or `strtoupper("x")`. A statement is an instruction that often wraps an expression (`$total = 5 + 3;`). Two places need no semicolon: the last statement before `?>` (because `?>` counts as one) and the closing brace of a `{ ... }` block such as a function or an `if`.
| Comment style | Where it ends | Typical use |
|---|---|---|
| `// note` | At the end of the line, or at `?>` | Short explanations |
| `# note` | Same as `//` | Rarely used; never start one with `#[` |
| `/* note */` | At `*/`; may span several lines | Longer notes, switching off a block |
| `/** ... */` | At `*/` | Docblocks read by IDEs and analysis tools |
Some names care about case and some do not. Variables (`$name` and `$Name` are different), constants and array keys are case-sensitive. Keywords (`echo`, `if`, `function`), function names (built-in and your own) and class names are not, so `ECHO` and `echo` are the same. Still, always write them the way they were declared; the widely used PSR-12 coding style asks for lowercase keywords.
Whitespace between tokens is free: newlines and indentation never change the meaning, except inside a string. A variable name starts with `$`, followed by a letter or underscore, then any mix of letters, digits and underscores. A statement may span several lines, which is how long function calls are made readable.
`declare(strict_types=1);` must come right after `<?php` as the very first statement of the file. It makes calls made from that file check types strictly. If any HTML or another statement comes first, PHP stops with `Fatal error: strict_types declaration must be the very first statement in the script`.
- Read the file top to bottom
- End every statement with `;`
- Skip comments and whitespace
- Variable names are case-sensitive
PHP compiles before it runs, so a parse error means nothing runs at all. Warnings, by contrast, appear while the script is running.
General pattern: the shape of a PHP file
<?php
declare(strict_types=1);
// comment, # comment, or /* block comment */
$variable = expression; // a statement ends with ;
functionName($argument); // a call is a statement too
if (condition) { // a block needs no ; after }
statement;
}An opening tag, one `declare` line, then statements. Assignments and function calls are statements and need `;`. The `}` that closes a `{ ... }` block needs no semicolon after it.
Example: a tour of the syntax
The script below has three comment styles, two variables whose names differ only in case, and a function. You should not normally write `ECHO` or `SHOUT(...)` like this; they are here only to show that keywords and function names ignore case. Predict the output before you run it.
<?php
declare(strict_types=1);
// A single-line comment
# Another single-line style
/* A block comment
can span several lines */
$Title = "Syntax tour";
$title = "a different variable"; // names are case-sensitive
ECHO $Title, PHP_EOL; // keywords are not (but write them in lowercase)
echo $title, PHP_EOL;
function shout(string $text): string
{
return strtoupper($text) . "!";
}
echo SHOUT("done"), PHP_EOL; // function names are not case-sensitive eitherCode breakdown
- Comments
# Another single-line style`//` and `#` run to the end of the line and `/* ... */` can cover several lines. PHP skips all three kinds.
- Two different variables
$Title = "Syntax tour";`$Title` and `$title` differ only in case, yet they are two separate variables, each with its own value.
- A keyword in capitals
ECHO $Title, PHP_EOL;The keyword `echo` ignores case, so `ECHO` works too. The variable `$Title`, however, must match its case exactly.
- A function declaration
function shout(string $text): string`strtoupper()` converts the text to capitals and `.` joins a `!` onto it. Declaring a function is not a statement that needs a semicolon after its closing `}`.
- Calling it in another case
echo SHOUT("done"), PHP_EOL;Function names ignore case, so `SHOUT(...)` calls `shout(...)` and the output is `DONE!`. In real code, write the name exactly as declared.
Syntax tour
a different variable
DONE!The closing tag and stray output
Leave out the `?>` in a file that contains only PHP. A space or newline after `?>` becomes part of the output. Once output has started in a web request, headers can no longer be sent, so a later `header()` call or session start can fail with the 'headers already sent' problem. Omitting the closing tag is the safer habit.
When a line break follows `?>` immediately, PHP drops that one line break from the output. In the example below the line break after each `?>` vanishes, so `line one` is followed by a new line and then a single `ABC` line. Also beware that a `?>` inside a `// note ?>` comment still ends PHP mode.
<?php $a = "x"; ?>
line one
<?php echo "A", "B"; ?>
CReading a parse error
The first line of an error message is the most useful part. The messages below were produced with PHP 8.3, and the wording can differ slightly between PHP 8.x releases. Do not trust the line number blindly; look at the line above it too.
| Mistake | Message (first part) |
|---|---|
| Missing `;` | `syntax error, unexpected token "echo"` |
| Unclosed string quote | `syntax error, unexpected identifier "world", expecting "," or ";"` |
| Unclosed `{` | `Unclosed '{' on line 2` |
| Extra `)` | `Unmatched ')'` |
In real projects
Syntax conventions in real projects
The PHP community mostly follows a coding style called PSR-12: lowercase keywords, four-space indentation and no closing `?>` in pure PHP files. Most projects also begin every file with `declare(strict_types=1);`. Tools such as PHP_CodeSniffer or PHP CS Fixer check these rules and fix them automatically.
Running `php -l` in a pre-commit hook and in CI stops files with parse errors from being committed or merged. Docblocks (`/** ... */`) are read by IDEs for autocomplete and by analysis tools such as PHPStan for type checking, so comments serve tools as well as people. With one shared style, a reviewer reads the logic of a pull request instead of its formatting, and the formatter fixes the rest.
Common mistakes
Common beginner mistakes
1. Looking at the wrong line
A missing `;` usually shows up on the next line. Do not spend an hour on the reported line; check the end of the line above and any quote or bracket that was never closed. `php -l file.php` reports such errors without running the script.
2. Mixing up the case of a variable name
After `$age = 25;`, writing `echo $Age;` gives `Warning: Undefined variable $Age`, yet the script carries on, so an empty value quietly appears in the output. Using one naming style (`$camelCase`) throughout makes this mistake rarer.
3. A `?>` or a `#[` inside a comment
In `// note ?> text` the `?>` closes PHP mode, so what follows becomes output instead of code. PHP 8 treats `#[` as the start of an attribute, so a comment like `#[Note]` causes a parse error. Put a space in `# [Note]` or just use `//`.
Mini challenge
Mini challenge: a weather summary
Write a `weather.php` script with all three comment styles, two variables `$city` and `$City`, and a `describe()` function. Call the function using different capitalisation to show that it still works.
- `describe(string $place, int $celsius): string` returns a string like `Yangon: 31 C`
- Use one `//`, one `#` and one `/* */` comment, plus a docblock above the function
- Give `$city` and `$City` two different city names
- Call it as `Describe(...)` and `DESCRIBE(...)`, then print the result of `$city === $City` as words
<?php
declare(strict_types=1);
// TODO: a docblock comment, then add the parameter and return types
function describe($place, $celsius)
{
// TODO: return "<place>: <celsius> C"
}
// TODO: two variables, $city and $City, holding different cities
// TODO: print both summaries, calling the function as Describe(...) and DESCRIBE(...)
// TODO: print "same variable" or "different variables" for $city === $CityExpected: Prints `Yangon: 31 C`, `Mandalay: 28 C` and `different variables`, one per line.
Show hint
You can build the string as `"{$place}: {$celsius} C"`. The ternary `$city === $City ? "same variable" : "different variables"` picks one of two words.
Show solution
<?php
declare(strict_types=1);
/**
* Builds a one-line weather summary.
*/
function describe(string $place, int $celsius): string
{
return "{$place}: {$celsius} C";
}
# two different variables, because variable names are case-sensitive
$city = "Yangon";
$City = "Mandalay";
echo Describe($city, 31), PHP_EOL; // function names ignore case
echo DESCRIBE($City, 28), PHP_EOL;
/* finally compare the two variables */
echo $city === $City ? "same variable" : "different variables", PHP_EOL;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Start a PHP file with `<?php` and make `declare(strict_types=1);` its first statement
- End every statement with `;`, and when a parse error appears the real mistake is often above the reported line
- There are three comment styles; beware that `?>` inside `//` ends PHP mode and that `#[` starts an attribute
- Variables, constants and array keys are case-sensitive, while keywords, functions and classes are not
Migrating to PHP 8.5 — PHP Documentation Group