Before moving further towards the syntax, lets first know what a syntax is ?
Syntax – Syntax is defined as the structure of statements or arrangement of statements to create well-formed sentence in a programming language. (Ex : Ram eats a mango)
This sentence is following an arrangement of noun verb and object to form a meaningful statement. Php’s syntax is very similar to other programming languages like (C, perl, java, e.t.c ).
The very first syntax which is mostly explained is
- Php statements starts with <?php and end with ?>
1 2 3 |
<?php // Script goes here ?> |
1 2 3 |
<? // Script goes here (It is not good practice, since it is not supported by all the server.) ?> |
It means all the php codes are written inside <?php and ?>
- The extension used to save our php file is .php (Ex : hello.php).
- A php file normally contains some html, css and other scripting language like javascript and others.
- Each Php statements end with a semicolon (;).
Remember : Whenever you save any html file which contains php script inside it, It must be saved with .php extension otherwise php code will not be executed at your browser window.
Lets take an example and clear all these syntax which is explained above :
Where echo is an inbuilt function which is used to print statement like (printf).
1 2 3 4 5 6 7 8 9 10 |
<html> <head> <title>My first PHP page</title> </head> <body> <?php echo "Hello PHP!"; ?> </body> </html> |
Output : Hello Php!
Semicolon : Never forgot to place semicolon (;) at the end of each php statement like programming language C. Semicolon is used to terminate the statement the current statement. Hence it is also known as statement terminator.
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head><title>My first PHP page</title></head> <body> echo "Hello PHP!"; <?php echo "Hello PHP!"; // semicolon (statement terminator on each line) echo "Hello PHP!"; echo "Hello PHP!"; ?> <body> <html> |
Output : Hello PHP! Hello PHP! Hello PHP!
White space : Like HTML, Php also ignores more than one space. In order to decorate your code (for better understanding of code). You can use tab or white space.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <head><title>My first PHP page</title></head> <body> echo "Hello PHP!"; <?php echo "Hello PHP!"; // White space of 2-3 lines but the output will be same echo "Hello PHP!"; ?> <body> <html> |
Output : Hello PHP! Hello PHP!