PHP Tags and Basic Syntax
Learning Objectives
- Master PHP programming concepts
- Write clean, maintainable code
- Apply best practices
- Build dynamic applications
Introduction to PHP
Welcome to our exploration of PHP tags and basic syntax! Today we're going to learn the fundamental building blocks of PHP code that will serve as the foundation for everything else you'll learn in this course.
PHP (which stands for PHP: Hypertext Preprocessor - a recursive acronym) is a server-side scripting language specifically designed for web development. It allows you to create dynamic web pages that can interact with databases, handle form submissions, manage sessions, and much more.
What makes PHP particularly powerful is how it seamlessly integrates with HTML. Unlike purely client-side languages like JavaScript, PHP code executes on the server and generates HTML that is then sent to the client. This means the browser receives only the processed HTML output, not the PHP code itself.
Analogy: Think of PHP as a chef in a restaurant kitchen. The customer (browser) makes an order (HTTP request), the chef (PHP) prepares the meal using ingredients (data, possibly from a database), and returns a finished dish (HTML) to the customer. The customer never sees the kitchen or the cooking process - only the final meal.
Basic PHP Syntax Rules
Like any language, PHP has rules that govern how you write code. Let's explore these fundamental syntax rules.
Statements and Semicolons
In PHP, each statement (a complete instruction) must end with a semicolon (;):
<?php
echo "Hello, World!";
$name = "John";
echo "Hello, " . $name;
?>
Forgetting semicolons is one of the most common mistakes for beginners and can cause syntax errors. Think of semicolons as the periods at the end of sentences in written language.
Exception: Closing PHP Tag
If a PHP block ends with a single statement, the semicolon before the closing PHP tag is technically optional (though still recommended for consistency):
<?php echo "Hello World" ?> <!-- Works but not recommended -->
<?php echo "Hello World"; ?> <!-- Recommended -->
Whitespace and Line Breaks
PHP generally ignores extra whitespace and line breaks, allowing you to format your code for readability:
<?php
// These are all equivalent:
echo "Hello World";
echo "Hello World";
echo
"Hello World" ;
?>
Analogy: PHP's handling of whitespace is like reading a book - whether the words are spaced closely or have extra space between them, the meaning stays the same.
Case Sensitivity
PHP is partially case-sensitive. Here are the rules:
| Element | Case Sensitive? | Example |
|---|---|---|
| Variables | Yes | $name and $Name are different variables |
| Functions (user-defined) | No | myFunction() and MYFUNCTION() are the same |
| Method names | No | $obj->method() and $obj->METHOD() are the same |
| Class names | No | new MyClass() and new myclass() are the same |
| Constants (defined with define()) | Yes by default | define("MY_CONST", 1, true) third parameter makes it case-insensitive |
| Class constants | Yes | MyClass::CONSTANT and MyClass::constant are different |
| Keywords (if, else, while, etc.) | No | if(), IF(), and iF() all work the same |
Despite some elements being case-insensitive, it's best practice to maintain consistent casing throughout your code for readability and maintainability.
Comments
Comments let you add notes to your code that are ignored by the PHP interpreter. They're essential for documenting your code and explaining complex logic.
<?php
// This is a single-line comment
# This is also a single-line comment (less common)
/*
This is a multi-line comment
that can span several lines
and is useful for longer explanations
*/
// Comments can be used to temporarily disable code too
// echo "This line won't execute";
echo "Hello World"; // You can add comments at the end of a line too
?>
PHP Code Blocks
A PHP code block is a section of PHP code enclosed by the PHP opening and closing tags. Within these blocks, you can include multiple statements, control structures, functions, and more:
<?php
// This entire section is a PHP code block
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo "Hello, " . $fullName . "!";
if (strlen($fullName) > 10) {
echo "You have a long name!";
} else {
echo "You have a short name.";
}
?>
You can have multiple PHP code blocks in a single file, interspersed with HTML:
<!DOCTYPE html>
<html>
<head>
<title>My PHP Page</title>
</head>
<body>
<?php
// First PHP block
$greeting = "Welcome to my website";
?>
<h1><?= $greeting ?></h1>
<p>This is regular HTML content.</p>
<?php
// Second PHP block
$currentTime = date("H:i:s");
echo "<p>The current time is: " . $currentTime . "</p>";
?>
</body>
</html>
PHP Output Methods
In PHP, there are several ways to output content to the browser. The most common methods are echo and print.
The echo Statement
echo is the most commonly used output method in PHP. It can output one or multiple strings:
<?php
// Basic echo
echo "Hello World!";
// Echo with HTML
echo "<h1>Welcome</h1><p>to my website.</p>";
// Echo multiple strings (without parentheses)
echo "Hello ", "World", "!";
// Variables in echo
$name = "John";
echo "Hello, " . $name . "!";
// Alternative syntax for embedding variables
echo "Hello, $name!";
?>
Quotes in PHP
Notice in the last example above that variables are automatically parsed inside double quotes (""), but not inside single quotes (''):
<?php
$name = "John";
echo "Hello, $name!"; // Outputs: Hello, John!
echo 'Hello, $name!'; // Outputs: Hello, $name!
?>
The print Statement
print is very similar to echo but has two key differences:
- It can only output one string (not multiple arguments)
- It returns a value (always 1), so it can be used in expressions
<?php
// Basic print
print "Hello World!";
// Print with HTML
print "<h1>Welcome</h1><p>to my website.</p>";
// Print with variables
$name = "John";
print "Hello, " . $name . "!";
// Using print in an expression
$result = (print "Hello") + 3; // $result will be 4
?>
echo vs print: Which to Use?
In most cases, echo and print can be used interchangeably, but echo is marginally faster since it doesn't return a value. For general output, echo is the standard choice among PHP developers.
| Feature | echo | |
|---|---|---|
| Can output multiple strings | Yes | No |
| Returns a value | No | Yes (always 1) |
| Can be used in expressions | No | Yes |
| Performance | Slightly faster | Slightly slower |
| Requires parentheses | Optional | Optional |
Other Output Methods
PHP provides several other output functions for specific purposes:
printf() and sprintf()
These functions allow formatted output similar to C's printf:
<?php
// printf() outputs the formatted string
$name = "John";
$age = 30;
printf("My name is %s and I am %d years old.", $name, $age);
// Outputs: My name is John and I am 30 years old.
// sprintf() returns the formatted string without outputting it
$message = sprintf("My name is %s and I am %d years old.", $name, $age);
echo $message;
?>
Common format specifiers include:
%s- String%d- Integer%f- Float (use %.2f for 2 decimal places)%b- Binary
var_dump() and print_r()
These functions are invaluable for debugging as they display detailed information about variables:
<?php
// var_dump() shows type and value information
$user = [
"name" => "John Doe",
"age" => 30,
"active" => true
];
var_dump($user);
/* Outputs something like:
array(3) {
["name"]=>
string(8) "John Doe"
["age"]=>
int(30)
["active"]=>
bool(true)
}
*/
// print_r() gives a more readable but less detailed output
print_r($user);
/* Outputs:
Array
(
[name] => John Doe
[age] => 30
[active] => 1
)
*/
?>
Practical Examples of PHP Tags and Syntax
Let's look at some real-world examples that demonstrate the use of PHP tags and basic syntax in different contexts.
Example 1: Simple Dynamic Content
A basic example showing how to include dynamic content in a webpage:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Website</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<?php
$currentHour = date('G');
if ($currentHour < 12) {
echo "<p>Good morning, visitor!</p>";
} elseif ($currentHour < 18) {
echo "<p>Good afternoon, visitor!</p>";
} else {
echo "<p>Good evening, visitor!</p>";
}
?>
<p>The current date and time is: <?= date("Y-m-d H:i:s") ?></p>
</body>
</html>
Example 2: HTML Template with Dynamic Data
Using PHP to loop through data and generate HTML content:
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
<style>
.product { border: 1px solid #ddd; padding: 10px; margin: 10px; }
.price { color: #c00; font-weight: bold; }
</style>
</head>
<body>
<h1>Our Products</h1>
<?php
// This array might come from a database in a real application
$products = [
[
"name" => "Laptop",
"price" => 999.99,
"description" => "Powerful laptop for all your needs"
],
[
"name" => "Smartphone",
"price" => 499.99,
"description" => "Latest model with advanced features"
],
[
"name" => "Headphones",
"price" => 79.99,
"description" => "Noise-cancelling wireless headphones"
]
];
?>
<div class="product-list">
<?php foreach ($products as $product): ?>
<div class="product">
<h2><?= $product["name"] ?></h2>
<p class="price">$<?= number_format($product["price"], 2) ?></p>
<p><?= $product["description"] ?></p>
</div>
<?php endforeach; ?>
</div>
<p><?= count($products) ?> products listed.</p>
</body>
</html>
Notice how we're using the alternative syntax for control structures (foreach (...): ... endforeach;) which is particularly useful when mixing PHP with HTML.
Example 3: Form Handling
Processing user input from a form:
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Us</h1>
<?php
// Initialize variables
$name = $email = $message = "";
$errors = [];
// Check if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
if (empty($_POST["name"])) {
$errors[] = "Name is required";
} else {
$name = trim($_POST["name"]);
}
// Validate email
if (empty($_POST["email"])) {
$errors[] = "Email is required";
} else {
$email = trim($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
}
// Validate message
if (empty($_POST["message"])) {
$errors[] = "Message is required";
} else {
$message = trim($_POST["message"]);
}
// If no errors, process the form
if (empty($errors)) {
// In a real app, you might save to a database or send an email here
echo "<div style='color: green;'>Thank you for your message! We will respond shortly.</div>";
// Reset form fields after successful submission
$name = $email = $message = "";
}
}
?>
<?php if (!empty($errors)): ?>
<div style="color: red;">
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="post" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?= htmlspecialchars($name) ?>">
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="<?= htmlspecialchars($email) ?>">
</div>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="5" cols="40"><?= htmlspecialchars($message) ?></textarea>
</div>
<div>
<button type="submit">Send Message</button>
</div>
</form>
</body>
</html>
This example demonstrates form handling, validation, and security practices like using htmlspecialchars() to prevent XSS attacks.
Example 4: Including External PHP Files
Breaking your code into reusable components:
header.php
<!DOCTYPE html>
<html>
<head>
<title><?= $pageTitle ?? 'My Website' ?></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="contact.php">Contact</a></li>
</ul>
</nav>
</header>
<main>
footer.php
</main>
<footer>
<p>© <?= date('Y') ?> My Website. All rights reserved.</p>
</footer>
</body>
</html>
index.php
<?php
// Set page-specific variables
$pageTitle = "Home Page";
// Include header
include "header.php";
?>
<h2>Welcome to My Website</h2>
<p>This is the home page content.</p>
<?php
// Include some dynamic content
$latestPosts = [
"Getting Started with PHP",
"Understanding PHP Tags",
"PHP Syntax Basics"
];
?>
<h3>Latest Posts</h3>
<ul>
<?php foreach ($latestPosts as $post): ?>
<li><?= $post ?></li>
<?php endforeach; ?>
</ul>
<?php
// Include footer
include "footer.php";
?>
This example demonstrates how to use include to separate your code into reusable components, a common practice in PHP development that helps maintain clean and organized code.
Best Practices for PHP Tags and Syntax
To write clean, maintainable PHP code, follow these best practices related to tags and syntax:
PHP Tags
- Always use standard PHP tags (
<?php ?>) for maximum compatibility - Use short echo tags (
<?= ?>) for simple output within HTML - Avoid short tags (
<? ?>) as they may not be enabled on all servers - Include a space after the opening tag and before the closing tag for readability
PHP Files
- Pure PHP files should omit the closing tag to prevent accidental whitespace output
- Files with mixed HTML and PHP should include the closing tag
- Begin files with the opening PHP tag at the top (no whitespace before it)
Coding Style
- Use consistent indentation (typically 4 spaces or a tab)
- Always include semicolons at the end of statements, even if optional
- Use descriptive variable and function names
- Follow a consistent naming convention (camelCase, snake_case, etc.)
- Add comments to explain complex code
Output and Security
- Always escape output in HTML contexts using
htmlspecialchars()to prevent XSS attacks - Prefer the alternative syntax (
if(): endif;,foreach(): endforeach;, etc.) when mixing PHP with HTML - Avoid complex PHP logic in templates - process data before outputting
Mixing PHP and HTML
- Separate business logic from presentation when possible
- Consider using a template engine for larger projects
- Use PHP includes to break code into manageable components
Tip: PSR Standards
The PHP Framework Interop Group (PHP-FIG) has established a set of PHP Standard Recommendations (PSRs) that define coding standards. PSR-1 (Basic Coding Standard) and PSR-12 (Extended Coding Style) are particularly relevant for syntax and style guidelines. Following these standards makes your code more consistent and easier for other developers to understand.
Common Mistakes and How to Avoid Them
Let's look at some common mistakes beginners make with PHP tags and syntax, and how to avoid them:
Syntax Errors
Mistake: Missing Semicolons
<?php
$name = "John"
echo "Hello, " . $name
?>
Correction:
<?php
$name = "John";
echo "Hello, " . $name;
?>
Mistake: Unclosed Quotes
<?php
echo "Hello, World!;
?>
Correction:
<?php
echo "Hello, World!";
?>
PHP Tag Issues
Mistake: Incorrect Tag Format
<? echo "Hello!"; ?> // Short tags may not be enabled
<% echo "Hello!"; %> // ASP tags are deprecated
<script language="php">echo "Hello!";</script> // Script tags are deprecated
Correction:
<?php echo "Hello!"; ?> // Standard tags always work
<?= "Hello!" ?> // Short echo tag is enabled by default in PHP 5.4+
Mistake: Nesting PHP Tags
<?php
echo "Hello";
<?php echo " World"; ?>
?>
Correction:
<?php
echo "Hello";
echo " World";
?>
Output Problems
Mistake: Unescaped Output
<?php
$userInput = $_GET['comment'];
echo "You said: " . $userInput; // Security vulnerability!
?>
Correction:
<?php
$userInput = $_GET['comment'] ?? '';
echo "You said: " . htmlspecialchars($userInput); // Safe output
?>
Mistake: Confusion with Quotes
<?php
$name = "John";
echo 'Hello, $name!'; // Variables don't expand in single quotes
?>
Correction:
<?php
$name = "John";
echo "Hello, $name!"; // Use double quotes for variable interpolation
// or
echo 'Hello, ' . $name . '!'; // Concatenation works with any quotes
?>
Whitespace and Headers
Mistake: Whitespace Before Opening PHP Tag
<?php
header('Location: index.php'); // Won't work - headers already sent
?>
Correction:
<?php
header('Location: index.php'); // Works - no output before header()
?>
Mistake: Unnecessary Closing Tags in Pure PHP Files
<?php
// Some PHP code
function doSomething() {
// Function code
}
?>
// Invisible whitespace here can cause problems
Correction:
<?php
// Some PHP code
function doSomething() {
// Function code
}
// No closing tag in pure PHP files
Practical Exercise: Creating a Basic PHP Template
Let's apply what we've learned by creating a basic PHP template that demonstrates proper tag usage and syntax.
Exercise Objectives
- Create a reusable PHP template with header and footer
- Implement proper PHP tag usage
- Practice outputting dynamic content
- Use PHP to handle conditional content
Template Files
Create the following files in your project directory:
1. config.php
<?php
// Site configuration
$siteConfig = [
'siteName' => 'My PHP Website',
'tagline' => 'Learning PHP Tags and Syntax',
'year' => date('Y'),
'navigation' => [
'Home' => 'index.php',
'About' => 'about.php',
'Services' => 'services.php',
'Contact' => 'contact.php'
]
];
// Function to determine if current page is active
function isActivePage($pageName) {
$currentPage = basename($_SERVER['PHP_SELF']);
return $pageName === $currentPage;
}
2. header.php
<?php
// Include configuration
require_once 'config.php';
// Set default page title if not provided
$pageTitle = $pageTitle ?? $siteConfig['siteName'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= htmlspecialchars($pageTitle) ?></title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 0; }
header { background-color: #333; color: white; padding: 1rem; }
.container { max-width: 1200px; margin: 0 auto; padding: 1rem; }
nav ul { list-style: none; padding: 0; display: flex; }
nav li { margin-right: 1rem; }
nav a { color: white; text-decoration: none; }
nav a.active { font-weight: bold; text-decoration: underline; }
main { min-height: 400px; }
footer { background-color: #333; color: white; padding: 1rem; text-align: center; }
</style>
</head>
<body>
<header>
<div class="container">
<h1><?= htmlspecialchars($siteConfig['siteName']) ?></h1>
<p><?= htmlspecialchars($siteConfig['tagline']) ?></p>
<nav>
<ul>
<?php foreach ($siteConfig['navigation'] as $name => $url): ?>
<li>
<a href="<?= $url ?>" class="<?= isActivePage($url) ? 'active' : '' ?>">
<?= htmlspecialchars($name) ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</nav>
</div>
</header>
<main class="container">
3. footer.php
</main>
<footer>
<div class="container">
<p>© <?= $siteConfig['year'] ?> <?= htmlspecialchars($siteConfig['siteName']) ?>. All rights reserved.</p>
<?php if (isset($showDebugInfo) && $showDebugInfo): ?>
<div style="font-size: 0.8rem; margin-top: 1rem;">
<p>Page rendered in <?= round((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000, 2) ?> ms</p>
</div>
<?php endif; ?>
</div>
</footer>
</body>
</html>
4. index.php
<?php
// Page-specific configuration
$pageTitle = "Home - PHP Tags and Syntax";
$showDebugInfo = true;
// Include header
include 'header.php';
?>
<h2>Welcome to our PHP Tags and Syntax Demo</h2>
<p>This is a demonstration of proper PHP tag usage and basic syntax.</p>
<h3>Server Time</h3>
<p>The current server time is: <?= date('Y-m-d H:i:s') ?></p>
<?php
// Array of PHP concepts we're learning
$phpConcepts = [
'PHP Tags',
'Basic Syntax',
'Output Methods',
'Variables',
'Conditionals',
'Loops'
];
?>
<h3>PHP Concepts We're Learning</h3>
<ul>
<?php foreach ($phpConcepts as $index => $concept): ?>
<li>
<strong>Concept <?= $index + 1 ?>:</strong>
<?= htmlspecialchars($concept) ?>
</li>
<?php endforeach; ?>
</ul>
<h3>Server Information</h3>
<p>You are running PHP version: <?= phpversion() ?></p>
<?php
// Include footer
include 'footer.php';
?>
5. about.php
<?php
// Page-specific configuration
$pageTitle = "About - PHP Tags and Syntax";
$showDebugInfo = true;
// Include header
include 'header.php';
?>
<h2>About This Template</h2>
<p>This template demonstrates the proper use of PHP tags and basic syntax in a real-world context.</p>
<h3>Features Demonstrated</h3>
<ul>
<li>Proper PHP tag usage</li>
<li>Including external files</li>
<li>Working with variables</li>
<li>Conditional output</li>
<li>Looping through arrays</li>
<li>Basic security practices</li>
</ul>
<?php
// Include footer
include 'footer.php';
?>
Exercise Instructions
- Create the five files listed above in your web server's document root
- Access index.php in your browser to see the template in action
- Try clicking the navigation links to see how the active page highlighting works
- Experiment by creating additional pages following the same pattern
- Modify the template to include additional features or styling
Additional Resources
Official Documentation
Tutorials and Guides
Books
- "PHP & MySQL: Novice to Ninja" by Kevin Yank
- "Modern PHP" by Josh Lockhart
- "Learning PHP, MySQL & JavaScript" by Robin Nixon