Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 147 ยท Getting Started

PHP Syntax

Learn PHP's basic syntax - opening and closing tags, when to omit ?>, statements and semicolons, blocks, case sensitivity, and mixing PHP with HTML using the short echo tag.

Every language has grammar rules, and PHP's are short. A PHP file is mostly ordinary text with PHP code inside special tags. Inside those tags, code is made of statements that end in semicolons and blocks wrapped in curly braces. A few names care about uppercase and lowercase, and a few don't.

This lesson covers those rules one by one: the <?php tag and when to leave out the closing ?>, how statements and blocks are written, what's case-sensitive, and how PHP mixes with HTML, including the handy <?= short echo tag. You saw several of these in Getting Started with PHP; now you'll learn exactly why they work.

PHP tags

PHP only runs the code between an opening tag <?php and a closing tag ?>. Anything outside the tags is inline content: PHP copies it to the output unchanged. That's why a .php file can be a complete HTML page with a few PHP islands in it.

PHP Code inside, text outside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is:

TEXT
This line is outside the tags, so it is printed as-is.
The current language is PHP, set by the code above.
And this line comes from echo.

PHP switched in and out of PHP mode three times. Notice that the variable $language survived: it's still one script, so variables set in one PHP block are available in the next.

There's one subtle detail. A newline that comes immediately after a closing ?> is swallowed by PHP. That's why there's no blank line after the first ?> in the output above. It was designed so that a closing tag at the end of a line doesn't leave stray line breaks in your HTML.

Omit the closing tag in pure PHP files

If a file contains only PHP code (a class, a function library, a configuration file), leave out the final ?>. The coding standards used across the PHP world (PSR-12 and its successor, PER Coding Style) require this, and for a good reason: anything after ?>, even a single space or an extra blank line, is sent to the output. In a file that's included by another script, that accidental whitespace can break things, most famously the "headers already sent" error you'll meet in HTTP Headers, Status Codes and Redirects.

PHP
<?php

declare(strict_types=1);

function formatPrice(int $cents): string
{
    return number_format($cents / 100, 2);
}
// No closing tag here: the file simply ends.

Use ?> only when you really switch back to HTML, as in templates.

Other tags you may see

  • <?= is the short echo tag, covered below. It's always available and widely used in templates.
  • <? on its own is the old "short open tag". It only works when the short_open_tag setting is on, so code using it breaks on many servers. Never use it; always write <?php.
  • <% ASP-style tags and <script language="php"> were removed in PHP 7. You may still spot them in very old code.

Statements and semicolons

A statement is one instruction: assign a value, call a function, print something. PHP statements end with a semicolon. Line breaks don't matter to PHP; the semicolon is what ends a statement:

PHP Statements and whitespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Whitespace (spaces, tabs, line breaks) between tokens is ignored, so you're free to format code for readability. The convention in modern PHP is one statement per line and 4 spaces of indentation.

Forget a semicolon and PHP can't parse the file. It's a parse error, so nothing in the file runs at all, not even the lines before the mistake. Run this example to see the error (it fails on purpose):

PHP A missing semicolon (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP reports:

TEXT
Parse error: syntax error, unexpected token "echo", expecting "," or ";" in main.php on line 4

The error points to line 4, but the mistake is at the end of line 3. PHP only noticed the problem when it found an unexpected echo where a ; should have been. When a parse error names a line that looks fine, check the line above it.

The one exception: the semicolon is optional on the last statement before a closing ?>, because the tag ends the statement. You'll see <?php echo $title ?> in templates. It's legal, but writing the semicolon anyway is never wrong.

Blocks and curly braces

Statements can be grouped into a block with curly braces { }. Blocks belong to control structures such as if, loops and functions, and they say which statements are controlled together:

PHP Blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A block doesn't need a semicolon after its closing brace. PHP allows an if without braces when there's only one statement, but the PHP style standards require braces every time, because adding a second line later without braces is a classic bug. You'll learn these structures properly in if, elseif and else and while, do-while and for Loops.

Case sensitivity

PHP is partly case-sensitive, which surprises people coming from other languages. Here are the rules:

Case-sensitive (exact case required) Case-insensitive (any case works)
Variable names: $name and $Name are different Keywords: echo, ECHO, If, foreach
Constants: PHP_EOL is not php_eol Function names: strlen(), StrLen()
Array keys: 'id' and 'ID' are different keys Class, interface and enum names
true, false and null in any case
PHP What is case-sensitive?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line ends the script on purpose with Fatal error: Uncaught Error: Undefined constant "php_eol". Everything before it prints normally.

Just because function names ignore case doesn't mean you should mix cases. Write keywords, functions, true, false and null in lowercase, and call functions and classes exactly as they're declared. Consistent code is easier to search and read, and static analysis tools will flag mismatched case.

Mixing PHP with HTML

Because inline content passes straight through, PHP works as a template language. The usual pattern is: do the logic in a PHP block at the top, then write HTML with small PHP pieces inside.

The short echo tag <?= expression ?> is shorthand for <?php echo expression; ?>. It keeps templates tidy:

PHP A small template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is the HTML source, because our editor shows plain text. On a web server, the browser would render a heading, a list and a paragraph:

HTML
<h1>Tea &amp; Coffee</h1>
<ul>
  <li>Green tea</li>
  <li>Espresso</li>
  <li>Chai &lt;spiced&gt;</li>
</ul>
<p>We serve 3 drinks.</p>

Three things to take from this example:

  • htmlspecialchars() turns characters like & and < into HTML entities, so data can never be mistaken for markup. Make it a reflex for every value you print into HTML. Preventing XSS explains the attacks it stops.
  • foreach (...): and endforeach; are the alternative syntax for control structures. Instead of braces scattered between HTML tags, the colon and the end...; keyword make templates easier to read. It exists for if, foreach, for, while and switch.
  • Each <?php ... ?> line ends with ?> followed by a newline, which PHP swallows, so no blank lines appear in the output.

PHP and HTML Templates builds on this with reusable templates and output buffering.

Putting it together: the anatomy of a PHP file

Here's what a typical modern PHP file looks like, with each syntax rule in place:

PHP Anatomy of a PHP file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

From top to bottom:

  1. <?php on the first line, with nothing before it.
  2. declare(strict_types=1); turns on strict type checking for this file. You'll meet it often; Type Declarations explains it fully.
  3. A constant (see Constants), a function with a block body, then the main code.
  4. One statement per line, each ending in ;, with 4-space indentation.
  5. No closing ?>, because the file is pure PHP.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a file that contains only PHP code leave out the closing ?> tag?

    Anything after ?>, even a stray space or blank line, is output. Omitting the closing tag avoids that, and PSR-12/PER require it.
  2. 2. Which line prints the same thing as <?php echo $title; ?>?

    <?= is the short echo tag and is always available. <? depends on a setting, and <% tags were removed in PHP 7.
  3. 3. After $Total = 10;, what does echo $total; do?

    Variable names are case-sensitive, so $total is a different, undefined variable. PHP warns and treats it as null, which echoes as nothing.
  4. 4. A file has a missing semicolon at the end of line 7 and an echo on line 2. What happens when it runs?

    The whole file is parsed before anything runs. A parse error means no part of the file executes.
  5. 5. Which of these is case-insensitive in PHP?

    Function names, keywords and class names ignore case. Variables, constants and array keys don't.

Summary

  • PHP code runs between <?php and ?>; text outside the tags is copied to the output unchanged.
  • In files that contain only PHP, omit the closing ?> to avoid accidental output. Never use the short <? tag.
  • Statements end with ;. A missing semicolon is a parse error that stops the whole file; check the line above the reported one.
  • Blocks use { }; always use braces with if and loops.
  • Variables, constants and array keys are case-sensitive; keywords, function names and class names aren't (but write them consistently).
  • <?= $value ?> prints a value in templates; escape with htmlspecialchars() and use the alternative syntax (foreach: ... endforeach;) in HTML.

Next: Comments, where you'll learn how to leave notes in your code and write DocBlocks that tools understand.