Skip to main content

📝 Lesson 3: PHP Syntax Basics

Time to learn the language itself. This lesson covers everything you need to start writing PHP — from opening tags to variables, data types, output, and the quirks of PHP's type system.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Use PHP opening and closing tags correctly
  • Declare and use variables following PHP naming rules
  • Identify and work with PHP's core data types (string, int, float, bool, null)
  • Output content using echo and print
  • Write single-line and multi-line comments
  • Understand PHP's type juggling and how to check types

Estimated Time: 45 minutes

Prerequisites: Lesson 2 (working LAMP environment)

📑 In This Lesson

PHP Tags

PHP code lives inside special tags that tell the server "process this as PHP." Everything outside these tags is treated as plain HTML and sent directly to the browser.

The Standard Tag

<?php
    // PHP code goes here
?>

This is the only tag style you should use. It works everywhere and is universally supported.

Mixing PHP and HTML

PHP files can contain both HTML and PHP. You can switch between them freely:

<!DOCTYPE html>
<html>
<body>
    <h1>Welcome</h1>
    <p>The current year is <?php echo date('Y'); ?></p>

    <?php
        $name = "PHP Student";
        $lessons = 24;
    ?>

    <p>Hello, <?php echo $name; ?>! You have <?php echo $lessons; ?> lessons ahead.</p>
</body>
</html>

✅ Best Practice: Omit the Closing Tag in Pure PHP Files

If a file contains only PHP (no HTML), leave off the closing ?> tag. This prevents accidental whitespace after the tag, which can cause "headers already sent" errors.

<?php
// Pure PHP file — no closing tag needed

$greeting = "Hello, World!";
echo $greeting;
// End of file — no ?> here

⚠️ Avoid These Tag Styles

You may see these in old code, but don't use them:

// Short open tag — depends on php.ini setting, not portable
<? echo "risky"; ?>

// ASP-style tags — removed in PHP 7
<% echo "deprecated"; %>

// Script tag — removed in PHP 7
<script language="php"> echo "ancient"; </script>

The one exception: <?= ... ?> is a shortcut for <?php echo ... ?> and is always available since PHP 5.4. It's fine to use in templates:

<p>Hello, <?= $name ?></p>
<!-- Same as: <?php echo $name; ?> -->

Statements and Semicolons

Every PHP statement ends with a semicolon (;). This tells PHP where one instruction ends and the next begins.

<?php
$name = "Alice";      // Statement 1
$age = 30;            // Statement 2
echo $name;           // Statement 3
echo " is ";          // Statement 4
echo $age;            // Statement 5

⚠️ Forgetting Semicolons

A missing semicolon is one of the most common PHP errors. If you see an error message like Parse error: syntax error, unexpected..., check for a missing semicolon on the line before the reported error line.

// This will cause an error
$name = "Alice"    // ← Missing semicolon!
echo $name;        // PHP reports the error here, but the problem is above

You can put multiple statements on one line, but don't — it makes code harder to read:

// Legal but ugly — don't do this
$a = 1; $b = 2; $c = $a + $b; echo $c;

// Much better — one statement per line
$a = 1;
$b = 2;
$c = $a + $b;
echo $c;

Comments

Comments are notes in your code that PHP ignores completely. They're for humans — future you, your teammates, or anyone reading the code.

Single-Line Comments

<?php
// This is a single-line comment (C++ style)
# This is also a single-line comment (shell style)

$price = 29.99; // You can put comments at the end of a line too

Multi-Line Comments

<?php
/*
  This is a multi-line comment.
  It can span as many lines as you need.
  Useful for longer explanations or temporarily
  disabling blocks of code.
*/

$tax_rate = 0.0825;

DocBlock Comments

DocBlock comments use a special format that documentation tools can read. You'll see these in professional PHP code:

<?php
/**
 * Calculate the total price including tax.
 *
 * @param float $price    The base price
 * @param float $taxRate  The tax rate (e.g., 0.0825 for 8.25%)
 * @return float          The total price with tax
 */
function calculateTotal($price, $taxRate) {
    return $price * (1 + $taxRate);
}

✅ Comment Guidelines

Good comments explain why, not what. The code itself shows what's happening; comments should explain the reasoning behind non-obvious decisions.

// Bad comment — restates the obvious
$count = $count + 1; // Add 1 to count

// Good comment — explains the why
$count = $count + 1; // Account for the header row in the CSV

Variables

Variables are containers that store data. In PHP, every variable starts with a dollar sign ($).

Declaring and Assigning Variables

<?php
// You don't need to declare types — just assign a value
$name = "Alice";          // A string
$age = 30;                // An integer
$price = 19.99;           // A float
$isStudent = true;        // A boolean
$middleName = null;       // Null (no value)

PHP variables are dynamically typed — you don't declare a type, and a variable can change types during its lifetime:

<?php
$x = 42;          // $x is an integer
$x = "hello";     // Now $x is a string — PHP doesn't complain
$x = 3.14;        // Now $x is a float

Variable Naming Rules

Rule Valid Invalid
Must start with $ $name name
First character after $ must be a letter or underscore $_count, $myVar $1name, $-value
Can contain letters, numbers, and underscores $user_2, $totalPrice $my-var, $my var
Case-sensitive $Name$name$NAME

Naming Conventions

PHP doesn't enforce a naming style, but most modern PHP code uses camelCase for variables:

<?php
// camelCase — recommended
$firstName = "Alice";
$totalPrice = 49.99;
$isLoggedIn = true;

// snake_case — also common, especially in older PHP / WordPress
$first_name = "Alice";
$total_price = 49.99;
$is_logged_in = true;

// Pick one style and be consistent!

📖 Variable Variables (Advanced)

PHP has a curious feature called "variable variables" where the name of a variable is itself stored in another variable. You'll rarely need this, but you should know it exists:

<?php
$field = "username";
$$field = "alice";     // Creates $username = "alice"
echo $username;        // Output: alice

Data Types

PHP has eight primitive types. In this lesson, we'll focus on the five you'll use most:

graph TD A["PHP Data Types"] --> B["Scalar Types"] A --> C["Compound Types"] A --> D["Special Types"] B --> E["string"] B --> F["int"] B --> G["float"] B --> H["bool"] C --> I["array
(Lesson 8)"] C --> J["object
(Lesson 16)"] D --> K["null"] D --> L["resource"] style E fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f style F fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f style G fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f style H fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f style K fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f style I fill:#f3f4f6,stroke:#9ca3af,color:#6b7280 style J fill:#f3f4f6,stroke:#9ca3af,color:#6b7280 style L fill:#f3f4f6,stroke:#9ca3af,color:#6b7280

String

A sequence of characters — text data. Enclosed in single quotes ('...') or double quotes ("...").

<?php
$greeting = "Hello, World!";
$path = '/var/www/html';
$empty = "";              // An empty string is still a string

echo strlen($greeting);   // Output: 13 (string length)
echo strtoupper($greeting); // Output: HELLO, WORLD!

Integer (int)

Whole numbers — positive, negative, or zero. No decimal point.

<?php
$count = 42;
$negative = -17;
$zero = 0;

// Different notations (all valid)
$decimal = 255;        // Decimal
$hex = 0xFF;           // Hexadecimal (= 255)
$octal = 0377;         // Octal (= 255)
$binary = 0b11111111;  // Binary (= 255)

// Underscores for readability (PHP 7.4+)
$million = 1_000_000;  // Same as 1000000

Float (Floating-Point / Double)

Numbers with a decimal point, or numbers in scientific notation.

<?php
$price = 19.99;
$pi = 3.14159265;
$tiny = 1.2e-3;       // Scientific notation: 0.0012
$big = 2.5E6;          // 2,500,000

⚠️ Float Precision

Floating-point numbers are not always exact. This is a fundamental computer science issue, not specific to PHP:

<?php
echo 0.1 + 0.2;         // Output: 0.30000000000000004
echo 0.1 + 0.2 == 0.3;  // Output: (empty — false!)

// For money, use integers (cents) or the bcmath extension
$priceInCents = 1999;    // $19.99 stored as cents

Boolean (bool)

A true/false value. Used heavily in conditions and comparisons.

<?php
$isActive = true;
$isAdmin = false;

// Booleans are case-insensitive (TRUE, True, true all work)
// Convention: use lowercase true/false

Null

Represents "no value" or "nothing." A variable is null if it has been assigned null, hasn't been assigned any value yet, or has been unset().

<?php
$data = null;

// Check if something is null
var_dump(is_null($data));    // bool(true)
var_dump(isset($data));      // bool(false) — isset returns false for null

Checking Types

Use var_dump() to inspect a variable's type and value — your best friend for debugging:

<?php
$name = "Alice";
$age = 30;
$price = 19.99;
$active = true;
$nothing = null;

var_dump($name);     // string(5) "Alice"
var_dump($age);      // int(30)
var_dump($price);    // float(19.99)
var_dump($active);   // bool(true)
var_dump($nothing);  // NULL

📊 var_dump vs. echo vs. print_r

PHP has several ways to output variable info:

  • echo $var — Outputs the value as a string. Fast, but doesn't show type info.
  • print_r($var) — Human-readable output. Great for arrays.
  • var_dump($var) — Shows type, length, and value. Best for debugging.

Rule of thumb: use echo for output, var_dump() for debugging.

Output: echo vs. print

PHP has two main ways to send output to the browser: echo and print. They're similar but not identical.

echo

<?php
// echo — the most common way to output
echo "Hello, World!";
echo "Hello", " ", "World!";   // echo accepts multiple arguments
echo("Hello!");                 // Parentheses are optional

// echo with HTML
echo "<h2>Welcome</h2>";
echo "<p>This is a paragraph.</p>";

print

<?php
// print — similar to echo
print "Hello, World!";
print("Hello!");

// print always returns 1, so it can be used in expressions
$result = print "test";  // Outputs "test", $result = 1

echo vs. print: The Differences

Feature echo print
Multiple arguments Yes: echo "a", "b"; No — only one argument
Return value None (void) Always returns 1
Speed Marginally faster Marginally slower
Use in expressions No Yes (because it returns 1)
Recommendation Use this by default Use when you need a return value

In practice, most PHP developers use echo almost exclusively. The speed difference is negligible.

Outputting Variables

<?php
$name = "Alice";
$age = 30;

// Concatenation with the dot (.) operator
echo "Name: " . $name . ", Age: " . $age;
// Output: Name: Alice, Age: 30

// Variable interpolation (double quotes only — see next section)
echo "Name: $name, Age: $age";
// Output: Name: Alice, Age: 30

// Curly brace syntax for clarity
echo "Name: {$name}, Age: {$age}";
// Output: Name: Alice, Age: 30

String Quoting: Single vs. Double

This is one of PHP's most important distinctions. Single-quoted and double-quoted strings behave differently:

Feature Single Quotes '...' Double Quotes "..."
Variable parsing No — $name is literal text Yes — $name is replaced with its value
Escape sequences Only \\ and \' Full set: \n, \t, \\, \", \$, etc.
Performance Marginally faster (no parsing) Marginally slower
<?php
$language = "PHP";

// Double quotes — variable IS parsed
echo "I love $language!";
// Output: I love PHP!

// Single quotes — variable is NOT parsed
echo 'I love $language!';
// Output: I love $language!

// Escape sequences
echo "First line\nSecond line";  // \n creates a newline
echo 'First line\nSecond line';  // \n is printed literally

When to Use Which?

  • Single quotes when the string has no variables and no special characters — slightly cleaner for simple strings
  • Double quotes when you want to embed variables or use escape sequences like \n
  • Concatenation when mixing gets complicated — sometimes 'Hello, ' . $name . '!' is clearer than "Hello, $name!"

Heredoc and Nowdoc (Multi-Line Strings)

For longer strings, PHP offers heredoc (like double quotes) and nowdoc (like single quotes):

<?php
$name = "Alice";

// Heredoc — variables ARE parsed (like double quotes)
$html = <<<HTML
<div class="card">
    <h2>Welcome, $name!</h2>
    <p>This is a heredoc string.</p>
</div>
HTML;

// Nowdoc — variables are NOT parsed (like single quotes)
$template = <<<'TEMPLATE'
<div class="card">
    <h2>Welcome, $name!</h2>
    <p>This is a nowdoc — $name stays as literal text.</p>
</div>
TEMPLATE;

echo $html;      // Shows: Welcome, Alice!
echo $template;   // Shows: Welcome, $name!

Type Juggling and Type Checking

PHP is loosely typed — it automatically converts between types when it thinks it's helpful. This is called type juggling (or type coercion).

Automatic Type Conversion

<?php
// PHP converts types automatically in certain contexts
$result = "5" + 3;
var_dump($result);  // int(8) — PHP converted "5" to integer 5

$result = "5.5" + 1.5;
var_dump($result);  // float(7) — PHP converted "5.5" to float

$result = true + true;
var_dump($result);  // int(2) — true becomes 1

$result = "hello" + 5;
var_dump($result);  // int(5) — "hello" becomes 0 (no leading digits)

Truthy and Falsy Values

When PHP converts a value to boolean (e.g., in an if statement), these values are considered falsy (they become false):

Falsy Value Type Notes
false bool The boolean false itself
0 int Integer zero
0.0 float Float zero
"" string Empty string
"0" string The string "0" (this surprises many people!)
[] array Empty array
null null The null type

Everything else is truthy — including "false" (the string), -1, and non-empty arrays.

💡 Key Gotcha: The string "0" is falsy in PHP. This catches many beginners off guard. if ("0") { ... } will not execute the block.

Explicit Type Casting

You can force a type conversion using casting:

<?php
$str = "42";

$num = (int) $str;       // Cast to integer
$flt = (float) $str;     // Cast to float
$bln = (bool) $str;      // Cast to boolean
$arr = (array) $str;     // Cast to array

var_dump($num);  // int(42)
var_dump($flt);  // float(42)
var_dump($bln);  // bool(true)
var_dump($arr);  // array(1) { [0]=> string(2) "42" }

Comparison Gotchas: == vs. ===

This is critical. PHP has two equality operators:

<?php
// == (loose comparison) — compares values after type juggling
var_dump(0 == "hello");    // bool(true) ← Surprise! (PHP 7)
var_dump("" == false);     // bool(true)
var_dump(null == false);   // bool(true)
var_dump("1" == true);     // bool(true)

// === (strict comparison) — compares value AND type
var_dump(0 === "hello");   // bool(false) ✓ Different types
var_dump("" === false);    // bool(false) ✓ Different types
var_dump(1 === 1);         // bool(true)  ✓ Same type and value
var_dump(1 === "1");       // bool(false) ✓ int vs string

✅ Best Practice: Use === (Strict Comparison)

Always prefer === and !== over == and !=. Strict comparison prevents an entire category of subtle bugs. The only time to use == is when you intentionally want type juggling (rare).

Type-Checking Functions

<?php
$value = 42;

is_string($value);   // false
is_int($value);      // true
is_float($value);    // false
is_bool($value);     // false
is_null($value);     // false
is_numeric($value);  // true (works for numeric strings too)
isset($value);       // true (variable exists and is not null)
empty($value);       // false (value is not falsy)

// gettype() returns the type as a string
echo gettype($value);  // "integer"

Constants

Constants are like variables, but once defined, their value cannot change. They're used for values that stay the same throughout your program.

Using define()

<?php
// define() — the traditional way
define("SITE_NAME", "PHP Foundations");
define("MAX_UPLOAD_SIZE", 5242880);  // 5 MB in bytes
define("TAX_RATE", 0.0825);

echo SITE_NAME;  // Output: PHP Foundations
// Note: no $ sign for constants

Using const

<?php
// const — the modern way (can be used at class level too)
const DB_HOST = "localhost";
const DB_NAME = "php_foundations";
const VERSION = "1.0.0";

define() vs. const

Feature define() const
Used inside conditionals Yes No
Accepts expressions Yes Only literal values (PHP < 8.1)
Works at class level No Yes
Convention Runtime definitions Compile-time definitions

Built-In Constants

PHP provides many useful predefined constants:

<?php
echo PHP_VERSION;       // e.g., "8.3.6"
echo PHP_INT_MAX;       // Max integer value
echo PHP_FLOAT_MAX;     // Max float value
echo PHP_EOL;           // System line ending (\n on Linux, \r\n on Windows)
echo PHP_OS;            // Operating system (e.g., "Linux")
echo __FILE__;          // Current file path (magic constant)
echo __LINE__;          // Current line number (magic constant)
echo __DIR__;           // Current directory (magic constant)

📖 Magic Constants

Constants that start and end with double underscores (like __FILE__) are called "magic constants." Their values change depending on where they're used. We'll see more of these as we progress through the course.

Hands-On Exercises

🏋️ Exercise 1: Personal Info Card

Objective: Practice variables, types, and output by creating a dynamic "about me" page.

Instructions:

  1. Create a file called exercise_03a.php in your /var/www/html/php-foundations/exercises/ folder
  2. Define variables for your name, age, favorite language, years of experience, and whether you're currently a student
  3. Use echo with double-quoted strings to output an HTML card displaying all the information
  4. Use var_dump() inside a <pre> tag to display the type of each variable

Starter Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Exercise 3A: Personal Info Card</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; }
        .card { background: #f8f9fa; border-radius: 8px; padding: 20px; margin: 15px 0; }
    </style>
</head>
<body>
    <?php
        // TODO: Define your variables here
        $name = "";
        $age = 0;
        $favLanguage = "";
        $yearsExperience = 0;
        $isStudent = false;
    ?>

    <div class="card">
        <h2>About Me</h2>
        <!-- TODO: Echo your info using double-quoted strings -->
    </div>

    <div class="card">
        <h2>Type Information</h2>
        <pre>
        <!-- TODO: Use var_dump() on each variable -->
        </pre>
    </div>
</body>
</html>
💡 Hint

Remember: double quotes allow variable interpolation. You can write echo "<p>Name: $name</p>"; to embed the variable directly in the string.

✅ Solution
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Exercise 3A: Personal Info Card</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; }
        .card { background: #f8f9fa; border-radius: 8px; padding: 20px; margin: 15px 0; }
    </style>
</head>
<body>
    <?php
        $name = "Alice Johnson";
        $age = 28;
        $favLanguage = "PHP";
        $yearsExperience = 3.5;
        $isStudent = true;
    ?>

    <div class="card">
        <h2>About Me</h2>
        <?php
            echo "<p><strong>Name:</strong> $name</p>";
            echo "<p><strong>Age:</strong> $age</p>";
            echo "<p><strong>Favorite Language:</strong> $favLanguage</p>";
            echo "<p><strong>Experience:</strong> $yearsExperience years</p>";
            echo "<p><strong>Student:</strong> " . ($isStudent ? "Yes" : "No") . "</p>";
        ?>
    </div>

    <div class="card">
        <h2>Type Information</h2>
        <pre><?php
            var_dump($name);
            var_dump($age);
            var_dump($favLanguage);
            var_dump($yearsExperience);
            var_dump($isStudent);
        ?></pre>
    </div>
</body>
</html>

🏋️ Exercise 2: Type Juggling Explorer

Objective: Explore PHP's type juggling by predicting then verifying the results of various operations.

Instructions:

  1. Create exercise_03b.php
  2. For each expression below, first predict what you think the result will be, then use var_dump() to check
<?php
// Predict the output of each, then run var_dump() to check

// 1. What type and value?
$a = "10" + 5;

// 2. What type and value?
$b = "10 apples" + 5;

// 3. True or false?
$c = (0 == "php");

// 4. True or false?
$d = (0 === "php");

// 5. True or false?
$e = ("" == null);

// 6. True or false?
$f = ("" === null);

// 7. What type and value?
$g = true + true + false;

// 8. True or false?
$h = ("0" == false);

// 9. True or false? (tricky!)
$i = ("0" == null);

// 10. What type and value?
$j = (int) "99 bottles";
✅ Answers
$a = "10" + 5;        // int(15) — "10" becomes 10
$b = "10 apples" + 5; // int(15) — PHP reads leading "10", ignores " apples"
$c = (0 == "php");     // bool(true) in PHP 7 — "php" becomes 0
                       // bool(false) in PHP 8 — changed behavior!
$d = (0 === "php");    // bool(false) — different types (int vs string)
$e = ("" == null);     // bool(true) — both are falsy
$f = ("" === null);    // bool(false) — string vs null
$g = true + true + false; // int(2) — 1 + 1 + 0
$h = ("0" == false);   // bool(true) — "0" is falsy
$i = ("0" == null);    // bool(false) — "0" is a non-empty string vs null
$j = (int) "99 bottles"; // int(99) — PHP reads leading digits

Note on #3: PHP 8 changed how 0 == "string" works. In PHP 7, the string was converted to 0, making them equal. In PHP 8, the comparison returns false. This is a major reason to use ===!

🎯 Quick Quiz

Question 1: Which is the correct way to declare a PHP variable?

Question 2: What's the difference between single and double quotes in PHP?

Question 3: What does var_dump("42") output?

Question 4: Which of these values is truthy in PHP?

Question 5: Why should you prefer === over ==?

Knowledge Check

Before moving on, make sure you can answer these questions confidently:

  1. What happens if you forget a semicolon at the end of a PHP statement?
  2. What character must every PHP variable name start with?
  3. Name PHP's five basic scalar/special types.
  4. What's the difference between echo and print?
  5. Why is the string "0" falsy in PHP?
  6. What does var_dump() show that echo doesn't?
✅ Quick Answers
  1. You get a parse/syntax error, usually reported on the next line.
  2. A dollar sign ($), followed by a letter or underscore.
  3. string, int, float, bool, null
  4. echo can take multiple arguments and has no return value; print takes one argument and returns 1. Both output text.
  5. PHP treats "0" as equivalent to the integer 0, which is falsy. It's a special case unique to PHP.
  6. var_dump() shows the variable's type and length (for strings), not just its value.

Summary

🎉 Key Takeaways

  • PHP tags: Use <?php ... ?> (or <?= ... ?> for short echo). Omit the closing tag in pure PHP files.
  • Variables: Start with $, are case-sensitive, dynamically typed, and don't require type declarations.
  • Five core types: string, int, float, bool, null
  • Output: Use echo for output, var_dump() for debugging.
  • Quotes: Double quotes parse variables; single quotes don't.
  • Type juggling: PHP auto-converts types — use === (strict comparison) to avoid surprises.
  • Constants: Use define() or const for values that never change.

📚 Additional Resources

🚀 What's Next?

Now that you know how to create variables and understand PHP's types, it's time to do things with them. In Lesson 4: Operators & Expressions, you'll learn arithmetic, comparison, logical, and string operators — the building blocks of every PHP program.

🎉 Congratulations!

You've learned PHP's syntax fundamentals — variables, types, output, and the type system. You're ready to start building logic!