Basic PHP Syntax
PHP code is introduced with a PHP opening tag. Expressions, statements and blocks describe its behavior; the dot operator concatenates strings.
Separate PHP code from surrounding output and identify statement boundaries.
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; ?>.