Web Analytics

PHP Syntax Basics

Beginner~20 min read

Understanding PHP's syntax rules is essential for writing clean, error-free code. In this lesson, you'll learn about statements, comments, case sensitivity, and other fundamental syntax rules that govern how PHP code is written.

PHP Statements

A statement is a single instruction that tells PHP to do something. Every statement must end with a semicolon (;):

Output
Click Run to execute your code
Statement Rules:
  • Each statement ends with a semicolon ;
  • Statements can span multiple lines
  • Multiple statements can be on one line (not recommended)
  • The last statement before ?> doesn't need a semicolon (but it's good practice)

Comments in PHP

Comments are notes in your code that PHP ignores. They're crucial for documenting your code and making it understandable:

Output
Click Run to execute your code
Comment Type Syntax Use Case
Single-line // comment Short notes, inline explanations
Single-line (alt) # comment Unix-style comments (less common)
Multi-line /* comment */ Longer explanations, multiple lines
Documentation /** comment */ PHPDoc format for functions/classes
Best Practices for Comments:
  • Explain why, not what (code should be self-explanatory)
  • Keep comments up-to-date with code changes
  • Use PHPDoc for functions and classes
  • Don't over-comment obvious code

Case Sensitivity

PHP has specific rules about case sensitivity that you must understand:

Output
Click Run to execute your code
Element Case Sensitive? Example
Variables ✅ Yes $name$Name
Constants ✅ Yes (by default) PIpi
Functions ❌ No echo = ECHO
Keywords ❌ No if = IF
Class names ❌ No MyClass = myclass
Important: Even though functions and keywords are case-insensitive, always use consistent casing! The PHP community standard is lowercase for keywords and functions.

Whitespace and Indentation

PHP is flexible with whitespace (spaces, tabs, newlines), but proper formatting makes code readable:

Output
Click Run to execute your code
Whitespace Rules:
  • Extra spaces between tokens are ignored
  • Newlines don't affect code execution
  • Indentation is for readability only (unlike Python)
  • Standard: 4 spaces per indentation level

Code Blocks

Code blocks group multiple statements together using curly braces {}:

<?php
// Single statement - no braces needed
if (true)
    echo "This works";

// Multiple statements - braces required
if (true) {
    echo "Statement 1";
    echo "Statement 2";
    echo "Statement 3";
}

// Always use braces for clarity (recommended)
if (true) {
    echo "Even for single statements";
}
?>
Pro Tip: Always use curly braces for code blocks, even with single statements. It prevents bugs when you add more statements later!

Naming Conventions

Following naming conventions makes your code more readable and professional:

Element Convention Example
Variables camelCase or snake_case $userName or $user_name
Functions camelCase or snake_case getUserName() or get_user_name()
Classes PascalCase UserAccount
Constants UPPER_SNAKE_CASE MAX_SIZE
Files lowercase, hyphen or underscore user-profile.php
PSR Standards: The PHP community follows PSR (PHP Standard Recommendations). PSR-12 defines coding style standards. Using these makes your code compatible with popular frameworks like Laravel and Symfony.

Closing PHP Tags

The closing ?> tag has special rules:

// File with only PHP - omit closing tag (recommended)
<?php
echo "Hello";
// No closing tag needed

// File with HTML after PHP - use closing tag
<?php
echo "Hello";
?>
<p>This is HTML</p>
Best Practice: For files containing only PHP code, omit the closing ?> tag. This prevents accidental whitespace from causing "headers already sent" errors.

Common Syntax Mistakes

1. Missing semicolons

<?php
$name = "John"  // ❌ Parse error!
echo $name      // ❌ Parse error!

$name = "John";  // ✅ Correct
echo $name;      // ✅ Correct
?>

2. Unclosed strings

<?php
echo "Hello;  // ❌ Unclosed string
echo 'World;  // ❌ Unclosed string

echo "Hello";  // ✅ Correct
echo 'World';  // ✅ Correct
?>

3. Nested comments

<?php
/*
  This is a comment
  /* This won't work! */  // ❌ Can't nest /* */ comments
*/

// Use single-line comments inside multi-line comments
/*
  This is a comment
  // This works fine  ✅
*/
?>

4. Variable name case mismatch

<?php
$userName = "John";
echo $username;  // ❌ Undefined variable (different case!)

$userName = "John";
echo $userName;  // ✅ Correct
?>

Exercise: Clean Code Practice

Task: Fix the following code to follow proper PHP syntax and conventions:

<?php
// Bad code - fix it!
$firstname = "john"
$LastName = "doe"
ECHO $firstname
echo $lastname
?>
Show Solution
<?php
// Fixed code with proper syntax and conventions
$firstName = "John";  // camelCase, capitalized name
$lastName = "Doe";    // Consistent casing
echo $firstName;      // Lowercase echo, semicolon
echo $lastName;       // Correct variable name
// Closing tag omitted for PHP-only files

Summary

  • Statements: End with semicolon ;
  • Comments: Use //, #, or /* */ to document code
  • Case Sensitivity: Variables are case-sensitive, functions/keywords are not
  • Whitespace: Flexible but use consistent indentation (4 spaces)
  • Code Blocks: Use {} to group statements
  • Naming: Follow PSR standards (camelCase for variables, PascalCase for classes)
  • Closing Tag: Omit ?> in PHP-only files
  • Best Practice: Write clean, consistent, well-commented code

What's Next?

Congratulations! You've completed Module 1 and learned the fundamentals of PHP. You now know what PHP is, how to install it, write your first programs, and understand basic syntax rules. In the next module, we'll dive into Variables & Data Types - learning how to store and manipulate data in PHP. Get ready to make your programs dynamic and interactive!