PHP Syntax
Syntax is the set of rules that defines how code must be written so the PHP engine can understand it. Just as a sentence needs correct grammar to be understood, a PHP script needs correct syntax to run. If the syntax is wrong, PHP cannot even begin executing the script — it stops with a parse error.
This lesson covers the rules that apply to every PHP script: where code goes, how statements end, how blocks are formed, how whitespace is treated, and what is and is not case-sensitive.
Basic Structure of a PHP Script
PHP code is written between an opening tag <?php and an optional closing tag ?>.
Syntax
<?php
// PHP code goes here
?>
Example
<?php
$language = "PHP";
$year = 1995;
echo "$language was first released in $year.";
Output
PHP was first released in 1995.
How It Works
<?phpswitches the engine into PHP mode. Everything after it is treated as code.- Each line ending in
;is a statement — one complete instruction. - Statements run from top to bottom, in order.
$languageand$yearmust be assigned before theecholine uses them. - The closing
?>is omitted because the file contains only PHP. This is the recommended style; the reason is explained in the PHP Tags lesson.
A PHP file can also contain HTML around the PHP blocks. Text outside the tags is sent to the output unchanged. That topic is covered in PHP and HTML.
Statements and Semicolons
What a Statement Is
A statement is a single instruction for PHP to carry out: assign a value, print text, call a function, and so on.
Why Semicolons Are Required
PHP does not use line breaks to decide where a statement ends. It uses the semicolon. This allows one statement to span several lines, or several statements to share a line.
Example
<?php
$price = 499;
$quantity = 3;
$total = $price * $quantity;
echo "Total: $total";
Output
Total: 1497
One Statement Across Several Lines
Because the semicolon marks the end, a long statement can be split for readability:
<?php
$message = "Order confirmed. "
. "Your items will be shipped "
. "within 2 business days.";
echo $message;
Output
Order confirmed. Your items will be shipped within 2 business days.
PHP reads from $message = until the semicolon after "within 2 business days." as one statement. The . operator joins the three strings.
Several Statements on One Line
<?php
$a = 5; $b = 10; echo $a + $b;
Output
15
This is valid, but it is harder to read and to debug, because error messages report a line number and all three statements share the same line. Use one statement per line in real code.
What Happens When a Semicolon Is Missing
<?php
$city = "Chennai"
echo $city;
Result
PHP Parse error: syntax error, unexpected token "echo" in /path/script.php on line 3
Why line 3? PHP reads $city = "Chennai" and expects either a semicolon or something that continues the expression (such as . for concatenation). It finds echo on line 3 instead, which cannot continue an assignment. PHP reports the line where it found the unexpected token, not the line where the semicolon is missing.
Rule of thumb: when a parse error points to a line that looks correct, check the end of the previous line.
The Last Statement Before a Closing Tag
The closing tag ?> automatically acts as a semicolon, so the last statement before it does not strictly need one:
<p><?php echo "Hello" ?></p>
This is valid and common in short template snippets. In blocks with several statements, still end every statement with ; so that adding a line later does not cause a parse error.
Code Blocks and Curly Braces
What a Code Block Is
A code block is a group of statements that belong together, wrapped in curly braces { }. Blocks are used by conditions, loops, functions, and classes to define which statements they control.
Example
<?php
$stock = 0;
if ($stock > 0) {
echo "In stock";
echo " - ready to ship";
} else {
echo "Out of stock";
echo " - notify me when available";
}
Output
Out of stock - notify me when available
How It Works
- The condition
$stock > 0isfalse, so PHP skips the first block entirely and runs theelseblock. - Both
echostatements inside the chosen block run, because the braces group them together. - A block does not end with a semicolon after
}. The statements inside it already end with semicolons.
What Happens Without Braces
PHP allows omitting the braces when a block contains a single statement:
<?php
$stock = 0;
if ($stock > 0)
echo "In stock";
echo " - ready to ship";
Output
- ready to ship
This output is wrong. Without braces, only the first statement after if belongs to the condition. The second echo always runs, regardless of its indentation. PHP ignores indentation entirely; only braces define blocks.
Best practice: always use braces, even for single-statement blocks. Coding standards such as PER Coding Style require them because this bug is easy to introduce and hard to notice.
Whitespace and Line Breaks
Whitespace means spaces, tabs, and line breaks. Outside of strings, PHP ignores extra whitespace. These three snippets are identical to PHP:
<?php
$total=$price*$quantity;
<?php
$total = $price * $quantity;
<?php
$total
=
$price
*
$quantity;
The second form is the readable one and follows common coding standards: one space around operators, one statement per line.
Where Whitespace Does Matter
- Inside strings, whitespace is part of the value:
<?php
echo "Hello World";
Output: Hello World (the four spaces are kept). In a browser, HTML collapses multiple spaces into one when rendering, but the spaces are still present in the HTML source.
Between keywords and names, at least one space is needed so that PHP can tell them apart.
echo$name;happens to work because$starts a new token, butfunctiongreet()does not work; it must befunction greet().After the opening tag,
<?phpmust be followed by whitespace (a space, tab, or line break).
Case Sensitivity
PHP's case rules are not uniform. Some names are case-sensitive and some are not. Knowing the difference avoids confusing bugs.
| Element | Case-Sensitive? | Example |
|---|---|---|
| Variables | Yes | $name and $Name are different variables |
| Constants | Yes | MAX_SIZE and max_size are different constants |
| Array keys (strings) | Yes | $user['Email'] and $user['email'] are different keys |
Keywords (echo, if, while, function) | No | ECHO and echo both work |
| Function names | No | strtoupper() and STRTOUPPER() call the same function |
| Class, interface, and trait names | No (for PHP itself) | new DateTime() and new datetime() both work |
| Method names | No | $date->format() and $date->FORMAT() both work |
true, false, null | No | TRUE and true are the same value |
Example: Variables Are Case-Sensitive
<?php
$price = 250;
echo "Price: $price\n";
echo "Price: $Price\n";
Output
Price: 250
PHP Warning: Undefined variable $Price in /path/script.php on line 5
Price:
Why This Happens
$price and $Price are two separate variables. Only $price has a value. When PHP reaches $Price, it finds no such variable, raises a warning, and treats the value as null, which is printed as an empty string. Since PHP 8.0, reading an undefined variable is a warning (it was a notice before), which makes this mistake more visible.
Example: Keywords and Functions Are Not Case-Sensitive
<?php
ECHO strtoupper("php") . "\n";
echo STRTOUPPER("php") . "\n";
Echo StrToUpper("php") . "\n";
Output
PHP
PHP
PHP
All three lines work because keywords and function names are matched regardless of case.
Why You Should Still Use Consistent Case
Even though PHP accepts different cases for functions and classes, always write names exactly as they are declared:
- Readability — code that writes the same function three different ways looks careless and is harder to search.
- Autoloading — when classes are loaded automatically from files (covered in Autoloading Classes and PSR-4 Autoloading), the class name is converted into a file path. On Linux servers, file names are case-sensitive.
new userController()may work on your Windows or macOS machine, where file systems are usually case-insensitive, and then fail on a Linux server with a "class not found" error because the file is namedUserController.php. - Coding standards — standard PHP style uses lowercase for keywords and
true,false, andnull.
Identifiers: Naming Rules
An identifier is a name you give to something: a variable, function, constant, or class. PHP enforces these rules:
- Must start with a letter or an underscore (
_). - After the first character, may contain letters, digits, and underscores.
- Cannot contain spaces, hyphens, or other punctuation.
- Variable names are always preceded by
$, but the$is not part of the identifier itself.
| Name | Valid? | Reason |
|---|---|---|
$userName | Yes | Starts with a letter |
$_count | Yes | Starts with an underscore |
$item2 | Yes | Digits allowed after the first character |
$2item | No | Starts with a digit |
$user-name | No | Hyphen is the minus operator; PHP reads $user - name |
$user name | No | Spaces are not allowed |
Common Naming Conventions
PHP does not enforce a naming style, but the community follows these conventions (from the PER Coding Style and PSR-1 standards):
| Element | Convention | Example |
|---|---|---|
| Variables | camelCase (snake_case is also common) | $orderTotal, $order_total |
| Functions | camelCase or snake_case — be consistent within a project | calculateTax() |
| Classes | PascalCase (StudlyCaps) | InvoiceGenerator |
| Methods | camelCase | sendEmail() |
| Constants | UPPER_SNAKE_CASE | MAX_UPLOAD_SIZE |
Descriptive names make code self-explanatory. $totalWithTax explains itself; $t2 does not.
Expressions vs Statements
These two terms appear throughout the PHP manual.
- An expression is anything that produces a value:
5,$price * 2,strtoupper("hi"),$a > $b. - A statement is a complete instruction that ends with a semicolon. Statements usually contain expressions.
Example
<?php
$discount = 100; // statement containing the expression 100
$final = 1500 - $discount; // statement containing the expression 1500 - $discount
echo $final > 1000 ? "High" : "Low"; // statement; the ternary is an expression
Output
High
Why the Distinction Matters
Some PHP features accept only expressions. For example, the match construct (covered in PHP Match) is an expression, so its result can be assigned to a variable or returned directly. An if statement cannot be assigned. Understanding which constructs produce values explains why $x = match(...) {...}; works but $x = if (...) {...}; does not.
An assignment is also an expression — its value is the assigned value. That is why chained assignment works:
<?php
$a = $b = 10;
echo $a + $b;
Output: 20. PHP evaluates $b = 10 first (value 10), then assigns that value to $a.
A Complete Example Using the Rules Together
The following script calculates an invoice. It uses statements, blocks, whitespace, case-sensitive variables, and descriptive identifiers.
<?php
const TAX_RATE = 0.18;
$customerName = "Ravi Kumar";
$unitPrice = 1200;
$quantity = 3;
$subtotal = $unitPrice * $quantity;
$tax = $subtotal * TAX_RATE;
$total = $subtotal + $tax;
if ($total > 4000) {
$shipping = 0;
} else {
$shipping = 99;
}
$grandTotal = $total + $shipping;
echo "Customer: $customerName\n";
echo "Subtotal: $subtotal\n";
echo "Tax (18%): $tax\n";
echo "Shipping: $shipping\n";
echo "Grand total: $grandTotal\n";
Output
Customer: Ravi Kumar
Subtotal: 3600
Tax (18%): 648
Shipping: 0
Grand total: 4248
Step-by-Step Explanation
const TAX_RATE = 0.18;defines a constant — a value that cannot change while the script runs. Using a named constant instead of writing0.18in several places means the rate is changed in one location. Constants are covered in PHP Constants.- Four variables hold the input data, each with a descriptive camelCase name.
$subtotal,$tax, and$totalare calculated in order. Each line depends on the line before it, which is why statement order matters.- The
if / elseblock chooses the shipping charge. Braces clearly mark which assignment belongs to which branch. - The
echostatements print the results.\ninside double quotes is a newline character, which places each value on its own line when the script runs in a terminal. In a browser, use<br>or HTML elements instead, because HTML treats newlines as spaces.
Notice that $tax prints as 648, not 648.0. The result of 3600 * 0.18 is a float, and PHP prints floats without unnecessary trailing zeros. Number formatting for currency (for example 648.00) is covered with number_format() and printf() in later lessons.
Common Syntax Errors
| Mistake | Typical Error | Fix |
|---|---|---|
| Missing semicolon | syntax error, unexpected token "..." on the next line | Add ; to the end of the previous statement |
Missing closing brace } | syntax error, unexpected end of file | Count opening and closing braces; editors highlight matching pairs |
| Missing closing quote | syntax error, unexpected end of file or an unexpected token far below | Close the string; check that quotes inside strings are escaped |
Variable without $ | Undefined constant "name" (an Error in PHP 8) | Write $name, not name |
| Wrong variable case | Warning: Undefined variable $Name | Use the exact name as assigned |
Checking Syntax Without Running the Script
The PHP CLI can check a file for syntax errors without executing it. This is called linting:
php -l script.php
Output when the file is valid:
No syntax errors detected in script.php
Output when it is not:
PHP Parse error: syntax error, unexpected token "echo" in script.php on line 3
Errors parsing script.php
Linting is safe to run on any file because nothing executes — no database writes, no emails, no output. It is commonly used in editors and in automated checks before code is deployed.
Best Practices
- One statement per line. Error messages point to lines; keeping statements separate makes errors easy to locate.
- Always use braces for blocks, even single-line ones.
- Indent with four spaces inside every block. PHP ignores indentation, but humans rely on it to see structure.
- Use consistent, descriptive names, and write functions and classes in the exact case they are declared.
- Omit the closing
?>tag in files that contain only PHP. - Follow a coding standard. The PHP Framework Interop Group's PER Coding Style (the successor to PSR-12) is the widely accepted standard. Tools such as PHP_CodeSniffer and PHP-CS-Fixer can check and fix style automatically.
- Lint before deploying.
php -lcatches syntax errors before they reach users.
Official reference: https://www.php.net/manual/en/language.basic-syntax.php