Skip to the workspace
Pebellslearn by building
Introduction to PHP  ›  Lesson

Basic PHP Syntax

Basic PHP Syntax 12 minPHP code is introduced with a PHP opening tag. Expressions, statements and blocks describe its behavior; the dot operator concatenates strings.

php / Basic PHP Syntax

Explore each scene at your own pace.

01 · The rule

The rule

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:

  • <?php opens 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 shows Price: $price literally.
  • Comments: // or # for one line, /* ... */ for several.
  • Case: variable names are case-sensitive ($title and $Title are different variables), but keywords and function names are not (ECHO works, though nobody writes it).

Inside HTML templates there is a short form: <?= $title ?> means <?php echo $title; ?>.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.