PHP basic syntax consists of the following:
- PHP tags
- Embedded with HTML
- Terminated by semicolon
- Comments
The file extension of PHP is .php
Example
1 |
basic.php, example.php |
PHP Tags
Every PHP programming file should have the following two tags:
- Open tag – <?php
- Close tag – ?>
A PHP program should be written between the open and close tag.
Instead of open tag, the short open tag (<?=) might be used. If we want to use short open tag we should change the INI setting in php.ini file like below:
1 |
short_open_tag = on; |
Example
1 2 3 |
<?php // PHP code goes here ?> |
Embedded With HTML
PHP file may or may not contain HTML contents. The presentation or view (one of the MVC) part should contain HTML section.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html> <head> </head> <body> <h1>Embedded With HTML</h1> <?php echo "Welcome to My PHP Programming"; ?> </body> </html> |
Terminated by semicolon
Every line between PHP open and close tag should be terminated by semicolon(;). If the open and close tags ended at the same line then the termination of semicolon is optional.
Following are valid examples
1 2 3 4 |
<?php echo "1st line Valid"; echo "2nd line Valid" // Semicolon missing but valid ?> |
Following are invalid examples
1 2 3 4 |
<?php echo "Invalid"// Semicolon missing. This is Invalid echo "Valid"; ?> |
Comments
Comments in PHP is same as C, C++ and Unix shell. The commented text or information will not be executed. The comment will describe the coding or functionality.
There are two types of comments available
- Single line comment
- Comment multiple lines
Single Line Comment
This type of comment will comment the single and same line from start to end.
Syntax
1 |
// |
We have to put // before the text to be commented.
Example
1 2 3 4 |
<?php // Below line will not provide any output // echo 'Hello! this line will not be printed'; ?> |
Comment Multiple Lines
This type of comment will comment both single and multiple lines.
Syntax
1 |
/* */ |
The content between/* and */ will be commented and will not provide any output.
Example
1 2 3 4 5 6 7 8 9 |
<?php // The following program does not execute the code between /* and */ /* $x = 5; $y = 2; $sum = $x+$y; echo $sum; // output 7 */ ?> |
Usage of comment
A good programmer should always write a comment in every PHP file and ensures that anyone can understand the functionality of the project and can able to continue the extension of the project without any one’s assistance.