PHP Syntax and Basic Structure

What You’ll Learn in This Chapter

  • Basic syntax rules of PHP
  • How to embed PHP within HTML
  • How to use echo and print
  • Comments in PHP
  • Writing clean, readable PHP code

Understanding PHP Syntax

PHP is embedded in HTML using special tags. The PHP parser only interprets code inside <?php ... ?> tags.

Basic Syntax Structure:

<?php
  // PHP code goes here
?>

Anything outside these tags will be treated as normal HTML.

Embedding PHP in HTML

PHP is commonly mixed with HTML. Here’s how that looks:

Example:

<!DOCTYPE html>
<html>
<head>
  <title>My First PHP Page</title>
</head>
<body>

<h1>Welcome to ScriptBuzz</h1>
<p>
  <?php
    echo "Today is " . date("l");
  ?>
</p>

</body>
</html>

Output:

Welcome to ScriptBuzz
Today is Sunday  ← (changes based on the actual day)

This is what makes PHP so powerful — it generates dynamic content within a standard HTML page.

Output Functions: echo vs print

Both are used to send output to the browser.

echo – Most commonly used:

echo "Hello, ScriptBuzz!";

print "Hello, ScriptBuzz!";

✔️ Use echo for better performance and simplicity.

PHP Comments

Use comments to make your code readable and maintainable.

Single-line comment:

// This is a comment
# This is also a single-line comment

Multi-line comment:

/*
  This is a multi-line
  comment block
*/

💡 Tip: Always comment your code to explain what each section does.

Semicolons, Case Sensitivity, and Whitespace

Semicolons:

Every PHP statement ends with a semicolon (;).

echo "Hello";  // Correct

Case Sensitivity:

  • Variable names are case-sensitive:
$name = "Jayesh";
echo $Name; // ❌ Error: undefined variable

  • Functions and keywords like echo, if, etc., are not case-sensitive:
ECHO "Hello World"; // ✅ This works

Whitespace:

PHP ignores extra spaces, tabs, or new lines. Use them to format code cleanly.

<?php
  // Set user name
  $name = "Jay";

  // Display greeting
  echo "<h2>Hello, $name!</h2>";
  echo "Welcome to ScriptBuzz.";
?>

Output:

Hello, Jay!
Welcome to ScriptBuzz.

✅ Best Practices

  • Always use meaningful variable names (e.g., $userName instead of $x)
  • End each statement with ;
  • Comment your code generously
  • Keep PHP logic clean and separate from presentation (HTML) when possible

Summary

  • PHP code is written between <?php ?> tags
  • Use echo or print to output data
  • Use comments to explain your code
  • Statements end with semicolons ;
  • PHP is case-sensitive with variables

Practice Challenge

Try this on your own:

  1. Create a file called greeting.php
  2. Inside it, define a variable $user = "John";
  3. Use echo to display:
Hello John, welcome to ScriptBuzz!

4. Add a comment above the code describing what the script does.