PHP Syntax

Course recommendation:

PHP scripts are executed on the server and then send back pure HTML results to the browser.

Basic PHP syntax

PHP scripts can be placed at any position in the document. <?php Start with ?> End:

<?php
// This is PHP code
?>

The default file extension for PHP files is ".php".

PHP files usually contain HTML tags and some PHP script code.

The following example is a simple PHP file that includes a PHP script using the built-in PHP function "echo" to output the text "Hello World!" on a web page:

Example

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

Run Instance

Comments:PHP statements end with a semicolon (;). The closing tag of a PHP code block also automatically indicates a semicolon (therefore, you do not need to use a semicolon on the last line of a PHP code block).

Comments in PHP

Comments in PHP code are not read and executed as a program. Their only purpose is to be read by the code editor.

Comments are used for:

  • Make others understand the work you are doing - comments can help other programmers understand the work you are doing at each step (if you work in a team)
  • Remind yourself of what you have done - most programmers have experienced going back to a project after one or two years and having to reconsider what they have done. Comments can record your thoughts when writing code.

PHP supports three types of comments:

Example

<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is a single-line comment
/*
This is a multiline comment block
It spans
Multiline
*/
?>
</body>
</html>

Run Instance

PHP Case Sensitivity

In PHP, all user-defined functions, classes, and keywords (such as if, else, echo, etc.) are not case-sensitive.

In the following example, all three echo statements are valid (equivalent):

Example

<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>

Run Instance

However, in PHP, all variables are case-sensitive.

In the following example, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are considered three different variables):

Example

<!DOCTYPE html>
<html>
<body>
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>

Run Instance