PHP Tutorial menu

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
<?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
<?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

php
<!DOCTYPE html>
<html>
<body>
<h2>Karachi Book Shop</h2>
<p>Books in stock: <?php echo 120; ?></p>
</body>
</html>
Output
Karachi Book Shop
Books in stock: 120

Statements and Semicolons

A statement is one instruction. Each statement ends with a semicolon ;.

Example

php
<?php
echo "Line one";
echo "<br>";
echo "Line two";
Output
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.

echoprint
Can output several valuesYes, separated by commasNo, only one
Returns a valueNoYes, always 1
SpeedSlightly fasterSlightly slower

Example

php
<?php
echo "Hello", " ", "Ali", "<br>";
print "Welcome to Workownix";
Output
Hello Ali
Welcome to Workownix

Most PHP developers use echo.

Comments

Comments are notes for people. PHP ignores them.

Example

php
<?php
// A single-line comment
# Also a single-line comment

/*
  A comment that covers
  several lines
*/

echo "Comments are not shown."; // a comment after code
Output
Comments are not shown.

Use comments to explain why your code does something, not just what it does.

Case Sensitivity

  • Keywords such as echo, if and while are not case sensitive. ECHO works, but always write lowercase.
  • Function names are not case sensitive either.
  • Variable names are case sensitive. $price, $Price and $PRICE are three different variables.

Example

php
<?php
$city = "Karachi";
echo $city;   // Karachi
echo $City;   // Warning: undefined variable

Exercise

Exercise

What must end most PHP statements?

Learn PHP with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp