PHP Syntax
Your First PHP Script
Section titled “Your First PHP Script”The Basic Structure
Section titled “The Basic Structure”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?>Hello World Example
Section titled “Hello World Example”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)
Alternative Syntax Options
Section titled “Alternative Syntax Options”PHP offers several ways to output content:
<?php// Using echoecho "Hello, World!";
// Using printprint "Hello, World!";
// Using printf for formatted outputprintf("Hello, %s!", "World");
// Short echo tag (if enabled in php.ini)<?= "Hello, World!" ?>?>Alternative PHP Tags
Section titled “Alternative PHP Tags”<!-- 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.
File Requirements
Section titled “File Requirements”- PHP files must have .phpextension
- 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 neededecho "Hello, World!";echo "This is pure PHP code";Embedding PHP within HTML
Section titled “Embedding PHP within HTML”One of PHP’s greatest strengths is its ability to be seamlessly embedded within HTML documents. This allows you to create dynamic web pages.
Basic HTML-PHP Integration
Section titled “Basic HTML-PHP Integration”<!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:
- The browser requests a .phpfile from the server.
- The server scans the file for PHP tags (<?php ... ?>).
- It executes only the code inside the tags. Any output from this code (e.g., from an echostatement) replaces the PHP block in that exact spot.
- Everything outside the tags is passed through unchanged.
- The server sends the final, combined result (which is now 100% pure HTML) back to the browser.
Multiple PHP Blocks in a Single File
Section titled “Multiple PHP Blocks in a Single File”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>Best Practices for Embedding PHP in HTML
Section titled “Best Practices for Embedding PHP in HTML”- 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>- 
Use Short Echo Tags for Simple Output: <?= $variable ?>instead of<?php echo $variable; ?>
- 
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 in PHP
Section titled “Comments in PHP”Comments are essential for documenting your code and making it readable for yourself and others. PHP supports several comment styles.
Single-Line Comments
Section titled “Single-Line Comments”Using double forward slashes (//):
<?php// This is a single-line commentecho "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 commentecho "Hello, World!"; # Another comment style
$age = 30; # User's age?>Multi-Line Comments
Section titled “Multi-Line Comments”Using /* ... */:
<?php/*This is a multi-line comment.It can span multiple lines.Useful for longer explanations or documentation.*/
echo "Hello, World!";
/*Author: John DeveloperDate: 2024Purpose: Demonstrate PHP commenting*/
$result = 10 * 5; /* Calculate the result */?>Documentation Comments (PHPDoc)
Section titled “Documentation Comments (PHPDoc)”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}?>Comment Best Practices
Section titled “Comment Best Practices”- 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;?>- 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>";?>- 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;}?>Common Syntax Rules and Conventions
Section titled “Common Syntax Rules and Conventions”PHP Tags
Section titled “PHP Tags”- Standard tags: <?php ... ?>(always supported)
- Short tags: <? ... ?>(must be enabled in php.ini)
- Echo tags: <?= ... ?>(shortcut for echo)
Statement Termination
Section titled “Statement Termination”<?phpecho "First statement";  // Semicolon requiredecho "Second statement"; // Semicolon required// Last statement in PHP block - semicolon still recommended?>Case Sensitivity
Section titled “Case Sensitivity”<?php// Keywords and functions are case-insensitiveECHO "Hello"; // Worksecho "Hello"; // WorksEcho "Hello"; // Works
// Variables ARE case-sensitive$name = "Alice";$Name = "Bob";    // Different variable!echo $name;       // Outputs: Aliceecho $Name;       // Outputs: Bob?>Common Mistakes to Avoid
Section titled “Common Mistakes to Avoid”- Forgetting semicolons:
<?phpecho "Hello World" // Missing semicolon - will cause errorecho "Second line";?>- Missing PHP tags:
<!-- This won't work - missing PHP tags -->echo "Hello World";
<!-- Correct way --><?php echo "Hello World"; ?>- Inconsistent quoting:
<?phpecho "Hello World'; // Mismatched quotes - will cause errorecho "Hello World"; // Correct?>