PHP Syntax

Every programming language has rules that govern how you write valid code — this is its syntax. PHP’s syntax defines how you switch between HTML and PHP code, how you end a statement, how you write comments, and how names like variables and functions are recognized. Get comfortable with these rules and everything else you learn about PHP will click into place much faster, because a single misplaced semicolon or brace is enough to stop a script from running at all. This lesson walks through PHP syntax from the ground up, including what actually happens when PHP reads your file.

Overview: How PHP Syntax Works

PHP is what’s called an embedded scripting language. A `.php` file is not pure code the way a `.c` or `.py` file usually is — it’s a mix of plain text (often HTML) with islands of PHP code dropped in wherever you need dynamic behavior. The PHP engine (called the Zend Engine) reads a file from top to bottom and treats everything as literal output except for the parts wrapped in special tags. The moment it sees <?php it switches into "PHP mode" and starts parsing real code; the moment it sees the matching ?> it switches back to "HTML mode" and simply prints whatever follows, character for character, until the next opening tag.

Inside PHP mode, code is organized into statements. A statement is a single instruction — assigning a variable, calling a function, looping, branching — and every statement must end with a semicolon (;), the same way an English sentence ends with a period. Statements can be grouped into blocks using curly braces { }, which is how PHP knows which statements belong to a function, an if, or a loop. Unlike Python, PHP does not care about indentation or line breaks at all — you could write an entire script on one line, or spread a single statement across ten lines, and PHP would parse it identically. Indentation in PHP is purely for humans.

Case sensitivity

PHP is inconsistent about case sensitivity, and this trips up a lot of beginners: variables are case-sensitive ($name and $Name are two completely different variables), but function names, class names, and keywords are case-insensitive (echo, ECHO, and Echo all work identically, and a function declared as myFunction() can be called as MYFUNCTION()). Good style always uses consistent casing anyway, but it helps to know the rule exists.

Syntax

The general shape of a PHP file looks like this:

<?php
// statement;
// statement;
?>
  • Everything between <?php and ?> is executed as PHP.
  • Everything outside those tags is sent to the output exactly as written (usually HTML).
  • A file that is pure PHP (no trailing HTML) conventionally omits the closing ?> tag entirely.
Element Meaning
<?php … ?> Standard opening/closing tags; always available regardless of server configuration.
<?= … ?> Short echo tag; shorthand for <?php echo ... ?>, always enabled since PHP 5.4.
; Terminates a statement. Required after every statement except the last one before a closing ?>.
{ } Delimit a block: function bodies, if/else branches, loops, classes.
// or # Starts a single-line comment; everything to the end of the line is ignored.
/* … */ Starts and ends a comment that can span multiple lines.
$variableName A variable: must start with $ then a letter or underscore, case-sensitive.

Examples

Example 1: Basic statements and output

<?php
$name = "Ada";
$age = 28;

echo "Hello, " . $name . "! You are " . $age . " years old.\n";
echo "Next year you will be " . ($age + 1) . ".\n";

Output:

Hello, Ada! You are 28 years old.
Next year you will be 29.

Two variables are declared and two echo statements print concatenated strings. Notice the semicolon at the end of each statement, and that string concatenation uses the dot (.) operator, not +.

Example 2: Comments and case sensitivity

<?php
// Function names are case-insensitive
function greetPerson($name) {
    return "Hi, $name!";
}

$color = "blue";
$Color = "red";

echo GREETPERSON("Sam") . "\n";
echo $color . "\n";
echo $Color . "\n";

/* Multi-line comments
   can span several lines */
# Hash-style single-line comment
echo "Done\n";

Output:

Hi, Sam!
blue
red
Done

Calling GREETPERSON() in all caps still finds the function greetPerson() because function names ignore case. But $color and $Color remain two independent variables, because variable names are case-sensitive. The script also shows all three comment styles PHP supports.

Example 3: Switching between PHP and HTML

<?php
$items = ["Pen", "Notebook", "Eraser"];
?>
<ul>
<?php foreach ($items as $index => $item): ?>
    <li><?= ($index + 1) . ". " . $item ?></li>
<?php endforeach; ?>
</ul>

Output:

<ul>
    <li>1. Pen</li>
    <li>2. Notebook</li>
    <li>3. Eraser</li>
</ul>

This is the classic "template" use of PHP: the script drops out of PHP mode to print raw HTML, then re-enters PHP mode using the alternative syntax (foreach (...): ... endforeach;) which is popular in templates because it avoids nested curly braces. The <?= ?> short echo tag prints the computed list number and item name directly inside the HTML.

How It Works Step by Step (Under the Hood)

  • Lexing: PHP first scans your raw file character by character and breaks it into tokens — words like echo, symbols like ;, string literals, variable names. Text outside <?php ?> tags is tokenized as a single "inline HTML" token to be printed verbatim.
  • Parsing: The token stream is assembled into an Abstract Syntax Tree (AST) that represents the structure of your program — which statements are inside which blocks, what belongs to which expression. This is also where syntax errors are caught: if braces don’t match or a semicolon is missing, the parser cannot build a valid tree and PHP throws a ParseError before executing a single line.
  • Compilation: The Zend Engine compiles the AST into low-level instructions called opcodes.
  • Execution: The Zend Virtual Machine executes the opcodes one by one, top to bottom, producing output and side effects as it goes.

One subtle but important rule: if a closing ?> tag is immediately followed by a single newline character, PHP swallows that newline instead of printing it. That’s why Example 3 above doesn’t produce stray blank lines between the HTML and the PHP blocks — the parser is quietly cleaning up the whitespace you’d otherwise get from every tag transition.

Common Mistakes

Mistake 1: Forgetting a semicolon

<?php
$total = 10 + 5
echo $total;

This throws a ParseError: syntax error, unexpected token "echo", because PHP expected the statement to end with ; before the next one began. The fix is simply to terminate every statement:

<?php
$total = 10 + 5;
echo $total;

Output:

15

Mistake 2: Mismatched braces

<?php
$age = 20;
if ($age >= 18) {
    echo "Adult";

The opening brace after if (...) is never closed, so PHP reaches the end of the file still expecting more code and fails with ParseError: unexpected end of file, expecting "}". Every opening brace needs a matching closing brace:

<?php
$age = 20;
if ($age >= 18) {
    echo "Adult";
}

Output:

Adult

Best Practices

  • Always use the full <?php ?> tags — short tags other than <?= ?> may be disabled and are not portable.
  • Omit the closing ?> tag in files that contain only PHP; it prevents accidental blank lines or whitespace from leaking into your output.
  • Use one statement per line and consistent indentation (most teams follow the PSR-12 style guide) even though PHP itself ignores whitespace — readability is for humans, not the parser.
  • Prefer // for short inline comments and /* */ for longer explanatory blocks or docblocks above functions and classes.
  • Keep casing consistent for functions and classes even though PHP doesn’t enforce it — relying on case-insensitivity makes code harder to read and search.
  • Run php -l yourfile.php (the built-in linter) before deploying to catch syntax errors early without executing the script.

Practice Exercises

  • Write a script that declares two variables, $first and $second, prints their values, swaps them using a third temporary variable, and prints them again to show the swap worked.
  • Write a script with a deliberate missing semicolon, then fix it. Note the exact wording of the ParseError message PHP gives you (you can check this with php -l if you have PHP installed locally).
  • Write a short PHP file that starts in HTML mode with a <p> tag, drops into PHP mode to compute the result of 7 * 6, and prints it using the short echo tag <?= ?> before closing the <p> tag.

Summary

  • PHP code lives between <?php and ?> tags; everything else is printed as-is.
  • Every statement must end with a semicolon; curly braces group statements into blocks.
  • Whitespace and indentation are ignored by PHP — they exist purely for readability.
  • Variable names are case-sensitive; function, class, and keyword names are not.
  • PHP supports //, #, and /* */ comment styles.
  • A newline immediately after ?> is swallowed by the parser, which keeps HTML/PHP transitions clean.
  • Syntax errors (missing semicolons, unmatched braces) are caught at parse time, before any code runs.