3-PHP Code Syntax
3-PHP Code Syntax
Like HTML, you need to have the opening tag to start PHP code:
<?php
If you mix PHP code with HTML, you need to have the enclosing tag:
?>
For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Syntax</title>
</head>
<body>
<h1><?php echo 'PHP Syntax'; ?></h1>
</body>
</html>
However, if a file contains only PHP code, the enclosing tag is optional:
<?php
echo 'PHP Syntax';
Case sensitivity
PHP is partially case-sensitive. Knowing what are case sensitive and what is not is very
important to avoid syntax errors.
If you have a function such as count, you can use it as COUNT. It would work properly.
• PHP constructs such as if, if-else, if-elseif, switch, while, do-while, etc.
• Keywords such as true and false.
• User-defined function & class names.
• On the other hand, variables are case-sensitive. e.g., $message and $MESSAGE
are different variables.
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:
$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. For example:
if( $is_new_user )
{
send_welcome_email();
}
You do not need to place the semicolon after the curly brace (}).
The closing tag of a PHP block (?>) automatically implies a semicolon (;). Therefore,
you do not need to place a semicolon in the last statement in a PHP block. For example:
In this example, the statement echo $name does not need a semicolon. However, using
a semicolon for the last statement in a block should work fine. For example:
Note that it is OK if the code may not make any sense to you now because you will
learn more about them in the upcoming tutorial.
And:
login(
$username,
$password
);
Summary
• PHP is partially case-sensitive.
• PHP constructs, function names, class names are case-insensitive, whereas
variables are case-sensitive.
• A statement ends with a semicolon (;).
• Whitespace and line breaks do not matter in PHP; do leverage them to make the
code more readable.