Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Introduction to PHP  ›  Lesson

Basic PHP Syntax

Basic PHP Syntax 12 minPHP code starts with the <?php tag, each statement ends with a semicolon, strings are joined with a dot, and double quotes fill in variables while single quotes do not.

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:

  • <?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; ?>.

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?

Fixing a broken lineStep 1 of 4
  1. The line

    echo 'Only $stock left' + "!" should print Only 3 left!.

Drills

Answer fast — trust the rule.

quick drill

Which operator joins two strings in PHP?

quick drill

With $title = "Dune";, what does echo 'Book: $title'; print?

quick drill

Why do style guides say to omit the closing ?> in a file that contains only PHP?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainFix the broken line

The line echo 'In stock: $stock' + " copies" is meant to print In stock: 3 copies. Explain every problem with it and write the corrected line.