PHP Tutorial PHP Advanced PHP References

PHP - Syntax



A PHP file is saved with .php extension and a PHP file normally contains HTML tags, and PHP scripts. A PHP scripts can be written anywhere in the file. The PHP parsing engine differentiates PHP script from other elements of the HTML page, this mechanism is known as escaping to PHP. There are four ways to achieve this.

  • Canonical PHP Tags: It starts with <?php and ends with ?>. Every PHP statement ends with a semicolon ;.

    <?php 
     //PHP codes 
    ?>
    

  • SGML or Short HTML Tags: It starts with <? and ends with ?>. Every PHP statement ends with a semicolon ;. This tag will work only when the short_open_tag setting in php.ini file is set to 'on'.

    <? 
     //PHP codes 
    ?>
    

  • ASP Style Tags: It starts with <% and ends with %>. Every PHP statement ends with a semicolon ;. This tag will work only when the setting in php.ini file is set to 'on' to allow %.

    <% 
     //PHP codes 
    %>
    

  • HTML Script Tags: This PHP tag is removed from PHP 7.0.0 and onwards, therefore no more used.

    <script language="php"> 
     //PHP codes 
    </script> 
    

Example:

The example below uses canonical PHP tags Pin a HTML page. It uses echo statement to print "Hello World!." in the page.

<!DOCTYPE html>
<html>
<body>

<h1>My WebPage</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

Is PHP Case Sensitive?

In PHP, reserved keywords (for example - if, else, elseif, echo, etc.), functions and class names are not case sensitive. In the example below, echo keyword is used in different cases which produces same result in each scenario.

<?php
$MyVariable = "Hello World!.";
echo "$MyVariable\n";
Echo "$MyVariable\n";
ecHo "$MyVariable\n";
?>

The output of the above code will be:

Hello World!.
Hello World!.
Hello World!.

The user-defined variables are case-sensitive. In the example below, the user-defined variable when used in different case, it throws an error.

<?php
$MyVariable = 100;
echo "$myvariable\n";
?>

The output of the above code will be:

PHP Warning:  Undefined variable $myvariable in Main.php on line 3

Semicolons

In a PHP program, the semicolon is a statement terminator. Each individual statement in PHP must be ended with a semicolon. It indicates that the current statement has been terminated and other statements following are new statements. For example - Given below are two different statements:

$MyVariable = 100;
echo "$myvariable\n";