Every PHP developer sees syntax errors every day. The skill is not avoiding them. It is reading them quickly. When PHP cannot understand your code at all, it shows a parse error and stops before running anything.
1. Missing semicolon
<?php
$a = 5
echo $a;
Parse error: syntax error, unexpected token "echo" in /path/to/index.php on line 3
The fix is $a = 5;. The error is on line 3, the real problem is on line 2.
2. Missing dollar sign
<?php
name = "Ravi";
Parse error: syntax error, unexpected token "=" in /path/to/index.php on line 2
Every variable starts with $.
3. Unclosed quote
<?php
echo "Hello;
Parse error: syntax error, unexpected end of file, expecting variable or "${" or "{$" in /path/to/index.php on line 2
A string that never ends swallows the rest of the file. PHP only notices at the end of the file, and the exact wording of the message can differ between PHP versions.
4. Missing closing bracket
<?php
if (true) {
echo "Yes";
Parse error: Unclosed '{' on line 2 in /path/to/index.php on line 3
PHP names the bracket it is missing. Count your { and }.
5. Mixing quotes
<?php
echo 'It's raining';
The apostrophe in It's ends the string early. Use double quotes ("It's raining") or escape it ('It\'s raining').
How to read a PHP error
Every message has the same parts:
- The type:
Parse error,Warning,Fatal error. - What went wrong: the sentence after the colon.
- The file and the line number.
Start at the reported line, then look at the lines just above it.
Use an editor with syntax highlighting
Exercise: fix three bugs
This code has three syntax mistakes. Find them all.
<?php
$city = "Delhi"
echo 'Welcome to $city;
Show the answer
There is a missing semicolon after "Delhi", an unclosed single quote, and single quotes do not print the variable’s value. A fixed version:
<?php
$city = "Delhi";
echo "Welcome to $city";
Welcome to Delhi