Skip to content

PHP Syntax

Every PHP script begins with the opening tag <?php and should end with the closing tag ?> (though the closing tag is optional at the end of a file).

Basic Syntax:

<?php
// Your PHP code goes here
?>

Let’s start with the traditional “Hello, World!” program:

<?php echo "Hello, World!"; ?>

Breakdown of the syntax:

  • <?php - Opening PHP tag (tells the server to start interpreting PHP code)
  • echo - PHP function used to output text
  • "Hello, World!" - String literal enclosed in double quotes
  • ; - Semicolon terminates the statement (required in PHP)
  • ?> - Closing PHP tag (optional at end of file)

PHP offers several ways to output content:

<?php
// Using echo
echo "Hello, World!";
// Using print
print "Hello, World!";
// Using printf for formatted output
printf("Hello, %s!", "World");
// Short echo tag (if enabled in php.ini)
<?= "Hello, World!" ?>
?>

<!-- Standard (recommended) -->
<?php echo "Hello, World!"; ?>
<!-- Short tags (must be enabled in php.ini) -->
<? echo "Hello, World!"; ?>
<!-- Echo shorthand -->
<?= "Hello, World!" ?>

Best practice: Always use the full <?php tag for maximum compatibility across servers.


  • PHP files must have .php extension
  • If file contains only PHP code, closing ?> tag can be omitted. This prevents accidental whitespace or characters from being sent to the browser.
  • If you are mixing both PHP and HTML, you will always use both the opening and closing tags.
<?php
// This file contains only PHP: no closing tag needed
echo "Hello, World!";
echo "This is pure PHP code";

One of PHP’s greatest strengths is its ability to be seamlessly embedded within HTML documents. This allows you to create dynamic web pages.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First PHP Page</title>
</head>
<body>
<h1><?php echo "Welcome to My Website!"; ?></h1>
<p>Today's date is: <?php echo date('Y-m-d'); ?></p>
<p>Current time: <?php echo date('H:i:s'); ?></p>
</body>
</html>

How it Works:

  1. The browser requests a .php file from the server.
  2. The server scans the file for PHP tags (<?php ... ?>).
  3. It executes only the code inside the tags. Any output from this code (e.g., from an echo statement) replaces the PHP block in that exact spot.
  4. Everything outside the tags is passed through unchanged.
  5. The server sends the final, combined result (which is now 100% pure HTML) back to the browser.

You can have multiple PHP code blocks within a single HTML document:

<!DOCTYPE html>
<html>
<head>
<title><?php echo "Dynamic Title"; ?></title>
</head>
<body>
<?php
$username = "John Doe";
$age = 25;
?>
<h1>User Profile</h1>
<p>Name: <?php echo $username; ?></p>
<p>Age: <?php echo $age; ?></p>
<?php
if ($age >= 18) {
echo "<p>You are eligible to vote!</p>";
} else {
echo "<p>You are not eligible to vote yet.</p>";
}
?>
</body>
</html>

  1. Separate Logic from Presentation: Place complex PHP logic at the top of the file
<?php
// PHP logic at the top
$pageTitle = "Home Page";
$currentUser = "Jane Smith";
$isLoggedIn = true;
?>
<!DOCTYPE html>
<html>
<head>
<title><?= $pageTitle ?></title>
</head>
<body>
<?php if ($isLoggedIn): ?>
<p>Welcome back, <?= $currentUser ?>!</p>
<?php else: ?>
<p>Please log in to continue.</p>
<?php endif; ?>
</body>
</html>
  1. Use Short Echo Tags for Simple Output: <?= $variable ?> instead of <?php echo $variable; ?>

  2. Alternative Syntax for Control Structures in HTML:

<?php if ($condition): ?>
<div>HTML content when condition is true</div>
<?php endif; ?>
<?php foreach ($items as $item): ?>
<li><?= $item ?></li>
<?php endforeach; ?>

Comments are essential for documenting your code and making it readable for yourself and others. PHP supports several comment styles.

Using double forward slashes (//):

<?php
// This is a single-line comment
echo "Hello, World!"; // Comment at the end of a line
$name = "Alice"; // Store the user's name
?>

Using hash symbol (#):

<?php
# This is also a single-line comment
echo "Hello, World!"; # Another comment style
$age = 30; # User's age
?>

Using /* ... */:

<?php
/*
This is a multi-line comment.
It can span multiple lines.
Useful for longer explanations or documentation.
*/
echo "Hello, World!";
/*
Author: John Developer
Date: 2024
Purpose: Demonstrate PHP commenting
*/
$result = 10 * 5; /* Calculate the result */
?>

For professional development, use PHPDoc style comments for functions and classes:

<?php
/**
* Calculates the area of a rectangle
*
* @param float $length The length of the rectangle
* @param float $width The width of the rectangle
* @return float The calculated area
*/
function calculateRectangleArea($length, $width) {
return $length * $width;
}
/**
* User class for managing user data
*
* @author Jane Developer
* @version 1.0
*/
class User {
// Class implementation
}
?>

  1. Explain WHY, not WHAT:
<?php
// Good: Explains the purpose
// Convert temperature from Celsius to Fahrenheit for US users
$fahrenheit = ($celsius * 9/5) + 32;
// Poor: States the obvious
// Multiply celsius by 9/5 and add 32
$fahrenheit = ($celsius * 9/5) + 32;
?>
  1. Use comments to separate code sections:
<?php
// ===== USER AUTHENTICATION =====
$username = $_POST['username'];
$password = $_POST['password'];
// ===== DATABASE CONNECTION =====
$host = 'localhost';
$dbname = 'users_db';
// ===== OUTPUT GENERATION =====
echo "<h1>Welcome, " . $username . "</h1>";
?>
  1. Comment complex logic:
<?php
/*
Calculate shipping cost based on weight and distance
- Base rate: $5
- Additional $2 per kg over 1kg
- Distance multiplier applies for zones > 100km
*/
$shippingCost = 5 + max(0, $weight - 1) * 2;
if ($distance > 100) {
$shippingCost *= 1.5;
}
?>

  • Standard tags: <?php ... ?> (always supported)
  • Short tags: <? ... ?> (must be enabled in php.ini)
  • Echo tags: <?= ... ?> (shortcut for echo)
<?php
echo "First statement"; // Semicolon required
echo "Second statement"; // Semicolon required
// Last statement in PHP block - semicolon still recommended
?>
<?php
// Keywords and functions are case-insensitive
ECHO "Hello"; // Works
echo "Hello"; // Works
Echo "Hello"; // Works
// Variables ARE case-sensitive
$name = "Alice";
$Name = "Bob"; // Different variable!
echo $name; // Outputs: Alice
echo $Name; // Outputs: Bob
?>

  1. Forgetting semicolons:
<?php
echo "Hello World" // Missing semicolon - will cause error
echo "Second line";
?>
  1. Missing PHP tags:
<!-- This won't work - missing PHP tags -->
echo "Hello World";
<!-- Correct way -->
<?php echo "Hello World"; ?>
  1. Inconsistent quoting:
<?php
echo "Hello World'; // Mismatched quotes - will cause error
echo "Hello World"; // Correct
?>