PHP Syntax

Every language has rules for writing code. These rules are called syntax. PHP syntax is simple, and if you know a little C or JavaScript it will look familiar.


PHP tags

PHP code is written inside tags. The server runs only the code between the tags, and the rest is sent to the browser as it is.

<?php
// PHP code goes here
?>
  • <?php is the opening tag and ?> is the closing tag.
  • A PHP file is saved with the .php extension.
  • If a file contains only PHP code, you should not write the closing tag. It avoids problems with extra blank lines.
  • There is also a short tag for echo: <?= $name ?>, which means the same as <?php echo $name; ?>.

Statements and semicolon

A PHP statement is an instruction, like printing text. Every statement must end with a semicolon (;). Forgetting it is the most common error of beginners.

<?php
echo "Hello, World!";
echo " Learning PHP is fun.";
?>

Output:

Tutorials Class - Output Window

Hello, World! Learning PHP is fun.


Case sensitivity

  • Not case-sensitive: keywords like echo, if, while and the names of functions and classes. So ECHO and echo work same.
  • Case-sensitive: variable names and constants. $name and $Name are two different variables.
<?php
$color = "red";

ECHO "I like " . $color . "<br>";
echo "I like " . $COLOR;
?>

The first line works. The second line gives a warning “Undefined variable $COLOR”, because the variable name is different.


PHP inside HTML

You can mix PHP with HTML in the same file. This is how dynamic pages are made.

<!DOCTYPE html>
<html>
<body>
    <h1><?php echo "Welcome to PHP"; ?></h1>
    <p>Current year: <?= date("Y"); ?></p>
</body>
</html>

The browser receives normal HTML, with the PHP code already replaced by its result.


White space and line breaks

PHP ignores extra spaces, tabs and blank lines, so you can format the code to make it readable. A statement can also continue on many lines until the semicolon.


Comments

Use //, # or /* ... */ to write notes that PHP ignores. Read PHP Comments.

Next chapter: PHP Variables.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Simple Tips for PHP Beginners
Experiment with Basic PHP Syntax Errors
Using phpinfo() – Display PHP Configuration & Modules
Interview Questions & Answers
What is the correct & common way to start and finish a PHP block of code?
What is the default extension of the PHP file?