Statements and semicolons
A PHP program is a list of statements: instructions that PHP carries out one after the other, from the top of the file to the bottom. Each statement ends with a semicolon.
<?php
echo "First\n";
echo "Second\n";
echo "Third\n";First
Second
ThirdThe semicolon is not optional. It is how PHP knows where one instruction stops and the next begins. Line breaks do not matter to PHP, which is why two statements can share a line, although that makes code harder to read:
<?php
echo "One "; echo "line\n";One lineBlocks and braces
Statements that belong together are grouped in a block with curly braces { and }. You will see blocks after if, loops, functions and classes:
<?php
$stock = 0;
if ($stock === 0) {
echo "Out of stock\n";
echo "Check back next week\n";
}Out of stock
Check back next weekThe indentation (four spaces is the common standard, called PSR-12) is for people, not for PHP. PHP only looks at the braces. Consistent indentation makes it obvious which statements are inside which block, so keep it tidy from the start.
Case sensitivity
PHP is partly case-sensitive, which surprises people:
- Variable names are case-sensitive.
$priceand$Priceare two different variables. - Keywords and function names are not.
echo,ECHOandEchoall work, and so dostrlen()andSTRLEN().
<?php
$price = 10;
$Price = 99;
ECHO "price is $price, Price is $Price\n";
echo strtoupper("works") . "\n";price is 10, Price is 99
WORKSEven though uppercase keywords work, everyone writes them in lowercase. Use lowercase keywords and pick one style for variable names (this course uses $camelCase, such as $orderTotal) so you never have two names that differ only by case.
Comments
Comments are notes for people reading the code. PHP ignores them completely. There are three forms:
<?php
// A single-line comment: everything after // on this line is ignored.
$note = "x"; # The hash sign also starts a single-line comment.
/*
A block comment can span
several lines.
*/
echo "Comments do not print anything\n"; // a comment can also follow codeComments do not print anythingA fourth form, the doc comment, starts with /**. It is still a comment to PHP, but editors and documentation tools read it to show what a function expects and returns:
<?php
/**
* Adds 18% tax to a price.
*
* @param float $price The price before tax.
* @return float The price including tax.
*/
function withTax(float $price): float
{
return $price * 1.18;
}
echo withTax(100) . "\n";118Good comments explain why the code does something, not what it obviously does. $total = $total * 1.18; // add 18% GST is helpful. $i = $i + 1; // add one to i is noise.
Comments are also handy for switching a line off while you experiment: put // in front of it instead of deleting it.
Syntax errors
If you break a rule, for example by forgetting a semicolon, PHP cannot understand the file and refuses to run any of it. This file is missing the semicolon after the first echo:
<?php
echo "Before the mistake\n"
echo "After the mistake\n";Parse error: syntax error, unexpected token "echo", expecting "," or ";" in /path/to/script.php on line 3Two things to learn from this message. First, the line number points to where PHP noticed the problem, which is often the line after the real mistake. Second, not even the first echo ran: PHP reads (parses) the whole file before running it. When you see "unexpected", look at the end of the previous line first.
On a development machine the message appears in the output, as above. A production server should hide it from visitors and write it to a log file instead, a setting covered in Errors and exceptions.
Whitespace
Spaces, tabs and blank lines between tokens are ignored, so $total=$a+$b; and $total = $a + $b; are identical to PHP. The second is far easier to read. Put spaces around operators, one statement per line, and a blank line between groups of related statements.
Common mistakes
- Missing semicolons, especially at the end of the line before an error message.
- Unbalanced braces: every
{needs a matching}. An editor that highlights matching braces helps. - Smart quotes pasted from a word processor or chat app (
“instead of"). PHP does not treat them as quotes. - Using HTML comments inside PHP code.
<!-- -->is only a comment in the HTML part of a file.
Exercise
The script below has three problems. Find and fix them, then run it. It should print Total: 30.
<?php
$a = 10
$b = 20;
// add the numbers
$total = $a + $B;
echo "Total: $total\n";Show one possible answer
The first line after the tag is missing a semicolon, $B should be $b because variable names are case-sensitive, and that typo would also print a warning about an undefined variable.
<?php
$a = 10;
$b = 20;
// add the numbers
$total = $a + $b;
echo "Total: $total\n";Total: 30Key points
- Every statement ends with a semicolon. Blocks of statements are grouped with curly braces.
- Variable names are case-sensitive; keywords and function names are not, but write them in lower case.
- Comments use //, # or /* ... */. Doc comments /** ... */ describe functions and classes for tools.
- A syntax error stops the whole file from running and names the line where PHP noticed the problem.