PHP Syntax
PHP code lives inside special tags embedded in a file, and each statement follows simple, consistent rules you will use in every program.
The basic PHP tags
A PHP script starts with the opening tag <?php and ends with the closing tag ?>. The web server executes only the code between these tags; anything outside them is treated as plain output and sent straight to the browser. This is what lets you sprinkle PHP into an HTML page wherever you need dynamic content. If you have not set up PHP yet, see the PHP Install lesson first.
Example
<?php
// All PHP statements go between the tags
echo "This text is generated by PHP.";
?>Statements and semicolons
Each instruction in PHP is called a statement, and every statement must end with a semicolon (;). The semicolon tells PHP where one instruction stops and the next begins. Forgetting it is one of the most common causes of syntax errors for beginners. Whitespace and line breaks between statements are ignored, so you are free to format your code for readability.
Example
<?php
$greeting = "Hello";
$name = "Ada";
echo $greeting . ", " . $name . "!";
?>Case sensitivity
PHP treats these two rules differently, which trips up many newcomers. Keyword and function names are not case sensitive, so echo, ECHO, and Echo all work the same. Variable names, however, are case sensitive: $name and $Name refer to two completely different variables. To stay safe, pick a consistent style and stick with it.
- Not case sensitive: keywords (if, else, while), function names, and class names
- Case sensitive: variable names, which always begin with a dollar sign ($)
Example
<?php
$color = "blue";
// echo and ECHO both work because keywords ignore case
ECHO $color;
// But $Color is a different variable and is empty here
echo $Color;
?>Adding comments
Comments are notes in your code that PHP ignores when running the script. They help explain what your code does, both to other people and to your future self. PHP supports single-line comments using // or #, and multi-line comments wrapped in /* and */.
Example
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multi-line comment.
It can span as many lines as you need.
*/
echo "Comments are ignored by PHP.";
?>Exercise: PHP Syntax
How does a block of PHP code begin inside a file?