Skip to main content

Basic PHP Syntax

Everything in a PHP script runs on the server, and the browser only ever receives the resulting plain HTML. You can put a script anywhere in a document. It opens with <?php and closes with ?>.

PHP files use .php as their default extension, and most of them mix HTML tags with PHP code.

Note: Every PHP statement has to finish with a semicolon (;).

Example

Here is a small .php file that mixes HTML with a line of PHP:

Prompt
Write a simple PHP file with HTML that displays an h1 heading "My first PHP page" and uses echo to output "Hello World!".
Output: PHP script

PHP script tags

These tags mark the beginning and the end of a block of PHP code:

index.php
<?php
// PHP code goes here
?>

PHP Case Sensitivity

PHP doesn't care about letter case in its keywords (such as if, else and echo), in class names or in function names, including the functions you write yourself. Variables are the exception: their names always have to match exactly, capitals included.

ECHO is the same as echo

Both spellings below are valid and print the same text, because ECHO and echo are the same keyword:

Prompt
Write a PHP script inside HTML that shows PHP keywords are not case-sensitive by using both ECHO and echo to print "Hello World!" followed by a line break.
Output: PHP script

$COLOR is not same as $color

Here $color has a value, but $COLOR is a separate variable that was never set, so it adds no text after "My house is":

Prompt
Write a PHP script inside HTML that demonstrates variable names are case-sensitive. Set $color to "red", then echo "My car is $color" and "My house is $COLOR" to show that $COLOR is not the same as $color.
Output: PHP script