PHP code
Like HTML, you need to have the opening tag to start PHP code:
1 | <?php |
If you mix PHP code with HTML, you need to have the enclosing tag:
1 | ?> |
Ex:
1 2 3 4 5 6 7 8 9 10 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Wrapline.pro</title> </head> <body> <h1><?php echo 'Syntax PHP'; ?></h1> </body> </html> |
However, if a file contains only PHP code, the enclosing tag is optional:
1 2 | <?php echo 'Syntax PHP'; |
Case sensitivity
PHP is partially case-sensitive. Knowing what are case sensitive and what is not is very important to avoid syntax errors.
In PHP, keywords (e.g. if
, else
, while
, echo
, etc.), classes, functions, and user-defined functions are not case-sensitive.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 | <!DOCTYPE html> <html> <body> <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> </body> </html> |
Output:
1 2 3 | Hello World! Hello World! Hello World! |
Note:
However, all variable names are case-sensitive!
If you have a function such as count
, you can use it as COUNT
. It would work properly.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <!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> |
Output:
1 2 3 | My car is red My house is My boat is |
Statements
A PHP script typically consists of one or more statements. A statement is a code that does something, e.g., assigning a value to a variable and calling a function.
A statement always ends with a semicolon (;
). The following shows a statement that assigns a literal string to the $message
variable:
1 | $message = "Hello"; |
The above example is a simple statement. PHP also has a compound statement that consists of one or more simple statements. A compound statement uses curly braces to mark a block of code:
1 2 3 | if( $is_new_user ) { send_welcome_email(); } |
You don’t need to place the semicolon after the curly brace (}
).
The closing tag of a PHP block (?>
) automatically implies a semicolon (;
). Therefore, you don’t need to place a semicolon in the last statement in a PHP block:
1 | <?php echo $name ?> |
However, using a semicolon for the last statement in a block should work fine:
1 | <?php echo $name; ?> |
Whitespace & line breaks
In most cases, whitespace and line breaks don’t have special meaning in PHP. Therefore, you can place a statement in one line or span it across multiple lines.
Ex:
1 | login( $username, $password ); |
and:
1 2 3 4 | login( $username, $password ); |