Basic PHP Syntax
Pageturn's first real page needs to show a book title and a price. Before any logic, PHP has a handful of writing rules: how code starts, how statements end, and how text is glued together. Get these right and most "unexpected token" errors disappear.
The rule
Open with
<?php, end each statement with;, glue strings with a dot.
<?php
// Pageturn: show one book
$title = "Dune";
$price = 9.99;
echo "Title: " . $title . "\n";
echo "Price: $price\n"; # double quotes fill in variables
echo 'Price: $price'; /* single quotes do not */Each part of the rule:
<?phpopens PHP mode. Anything outside the tags is sent out as plain text. In a file that holds only PHP, leave out the closing?>, so no stray blank line after it can sneak into the output.;ends a statement. Forgetting it is the most common beginner error. The final statement right before a?>may omit it, but do not rely on that..joins strings.+is for numbers only.- Quotes matter. Double quotes interpolate variables and understand escapes such as
\n. Single quotes print exactly what is written, so the last line above showsPrice: $priceliterally. - Comments:
//or#for one line,/* ... */for several. - Case: variable names are case-sensitive (
$titleand$Titleare different variables), but keywords and function names are not (ECHOworks, though nobody writes it).
Inside HTML templates there is a short form: <?= $title ?> means <?php echo $title; ?>.
The shortcut
Read a line of PHP in three passes: tags, semicolons, quotes. Is it inside <?php? Does each statement end with ;? Which kind of quotes hold the text?
The line
echo 'Only $stock left' + "!"should printOnly 3 left!.
Drills
Answer fast — trust the rule.
Which operator joins two strings in PHP?
With $title = "Dune";, what does echo 'Book: $title'; print?
Why do style guides say to omit the closing ?> in a file that contains only PHP?
Which pair names two different variables?
Remember
- Open with
<?php, end each statement with;, glue strings with a dot. - Shortcut: check tags, semicolons, quotes, in that order.
- Trap: single quotes do not fill in variables, and
+does not join text.
