PHP Syntax
Every PHP script follows a few simple rules. Learn them once and the rest of the language is easier.
The PHP Tag
PHP code starts with <?php and ends with ?>:
Example
<?php
echo "This is PHP.";
?>If a file contains only PHP code, you can leave out the closing ?>. This is the recommended style, because it avoids extra blank spaces being sent to the browser by mistake.
Example
<?php
echo "A file with only PHP code.";Mixing PHP and HTML
A PHP file can hold normal HTML. PHP only runs inside its tags:
Example
<!DOCTYPE html>
<html>
<body>
<h2>Karachi Book Shop</h2>
<p>Books in stock: <?php echo 120; ?></p>
</body>
</html>Karachi Book Shop Books in stock: 120
Statements and Semicolons
A statement is one instruction. Each statement ends with a semicolon ;.
Example
<?php
echo "Line one";
echo "<br>";
echo "Line two";Line one Line two
Forgetting a semicolon is the most common beginner error. PHP will show a "syntax error, unexpected..." message with a line number. Check the line just before it.
echo and print
Both send output to the page.
| echo | ||
|---|---|---|
| Can output several values | Yes, separated by commas | No, only one |
| Returns a value | No | Yes, always 1 |
| Speed | Slightly faster | Slightly slower |
Example
<?php
echo "Hello", " ", "Ali", "<br>";
print "Welcome to Workownix";Hello Ali Welcome to Workownix
Most PHP developers use echo.
Comments
Comments are notes for people. PHP ignores them.
Example
<?php
// A single-line comment
# Also a single-line comment
/*
A comment that covers
several lines
*/
echo "Comments are not shown."; // a comment after codeComments are not shown.
Use comments to explain why your code does something, not just what it does.
Case Sensitivity
- Keywords such as
echo,ifandwhileare not case sensitive.ECHOworks, but always write lowercase. - Function names are not case sensitive either.
- Variable names are case sensitive.
$price,$Priceand$PRICEare three different variables.
Example
<?php
$city = "Karachi";
echo $city; // Karachi
echo $City; // Warning: undefined variableExercise
Exercise
What must end most PHP statements?
