PHP - Syntax


Advertisements

Previous Page Next Page

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 below example 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 below example, echo keyword is used in different cases which produces same result in each scenario.

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

Output

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

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

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

Output

Undefined variable: myvariable

Previous Page Next Page
Advertisements