Web Analytics

PHP If Statements

Beginner~25 min read

Conditional statements allow your program to make decisions based on conditions. The if statement is the most fundamental control structure in PHP, letting you execute code only when specific conditions are met.

Basic If Statement

The simplest form executes code when a condition is true:

<?php
if (condition) {
    // Code executes if condition is true
}
?>
Part Description
if Keyword that starts the conditional
(condition) Expression that evaluates to true or false
{ } Code block to execute when condition is true
Output
Click Run to execute your code

If-Else Statement

Use else to execute alternative code when the condition is false:

<?php
$age = 16;

if ($age >= 18) {
    echo "You can vote!";
} else {
    echo "You're too young to vote.";
}
// Output: You're too young to vote.
?>
Best Practice: Always use curly braces { } even for single-line statements. It prevents bugs when adding more code later and improves readability.

If-Elseif-Else Statement

Check multiple conditions in sequence using elseif:

<?php
$score = 85;

if ($score >= 90) {
    $grade = 'A';
} elseif ($score >= 80) {
    $grade = 'B';
} elseif ($score >= 70) {
    $grade = 'C';
} elseif ($score >= 60) {
    $grade = 'D';
} else {
    $grade = 'F';
}

echo "Grade: $grade";  // Output: Grade: B
?>
Note: PHP accepts both elseif (one word) and else if (two words). They behave identically with curly brace syntax.

Multiple Conditions

Combine conditions using logical operators:

Operator Name Description
&& or and AND True if both conditions are true
|| or or OR True if at least one condition is true
! NOT Inverts the condition
<?php
$age = 25;
$hasLicense = true;
$hasCar = false;

// AND: both must be true
if ($age >= 18 && $hasLicense) {
    echo "You can drive legally.\n";
}

// OR: at least one must be true
if ($hasCar || $hasLicense) {
    echo "You have some driving capability.\n";
}

// NOT: inverts the condition
if (!$hasCar) {
    echo "You don't own a car.\n";
}
?>

Nested If Statements

Place if statements inside other if statements for complex logic:

<?php
$isLoggedIn = true;
$isAdmin = false;
$hasPermission = true;

if ($isLoggedIn) {
    echo "Welcome!\n";

    if ($isAdmin) {
        echo "You have full access.\n";
    } else {
        if ($hasPermission) {
            echo "You can view this content.\n";
        } else {
            echo "Access denied.\n";
        }
    }
} else {
    echo "Please log in.\n";
}
?>
Caution: Avoid deeply nested if statements (more than 2-3 levels). They become hard to read and maintain. Consider using early returns or restructuring your logic.

Alternative Syntax

PHP provides an alternative syntax useful when mixing PHP with HTML in templates:

<?php $userType = "premium"; ?>

<?php if ($userType === "premium"): ?>
    <div class="premium-badge">Premium Member</div>
<?php elseif ($userType === "basic"): ?>
    <div class="basic-badge">Basic Member</div>
<?php else: ?>
    <div class="guest-badge">Guest</div>
<?php endif; ?>
Output
Click Run to execute your code

Truthy and Falsy Values

PHP automatically converts values to boolean in conditions. Understanding what's "falsy" is crucial:

Falsy Values (evaluate to false) Truthy Values (evaluate to true)
false true
0 and 0.0 Non-zero numbers
"" and "0" Non-empty strings (including "false")
[] (empty array) Non-empty arrays
null Objects, resources
<?php
$name = "";

if ($name) {
    echo "Hello, $name!";
} else {
    echo "Name is empty!";  // This executes
}

// Better: be explicit
if ($name !== "") {
    echo "Hello, $name!";
}
?>
Pro Tip: Use strict comparisons (=== and !==) when checking specific values to avoid unexpected type coercion.

Common Mistakes

1. Using = instead of == or ===

<?php
$status = "active";

// โŒ WRONG: This assigns "inactive" to $status!
if ($status = "inactive") {
    echo "Account disabled";  // Always executes!
}

// โœ… CORRECT: Use == or ===
if ($status === "inactive") {
    echo "Account disabled";
}
?>

2. Forgetting braces with multiple statements

<?php
$loggedIn = true;

// โŒ WRONG: Only first line is conditional!
if ($loggedIn)
    echo "Welcome!\n";
    echo "Dashboard loaded\n";  // Always executes!

// โœ… CORRECT: Use braces
if ($loggedIn) {
    echo "Welcome!\n";
    echo "Dashboard loaded\n";
}
?>

3. Not handling all cases

<?php
$role = "moderator";

// โŒ Incomplete: What about other roles?
if ($role === "admin") {
    echo "Full access";
} elseif ($role === "user") {
    echo "Limited access";
}
// "moderator" gets nothing!

// โœ… CORRECT: Handle all cases
if ($role === "admin") {
    echo "Full access";
} elseif ($role === "user") {
    echo "Limited access";
} else {
    echo "Unknown role: $role";
}
?>

Exercise: User Access Control

Task: Create an access control system that determines what a user can do.

Requirements:

  • Check if user is logged in
  • If logged in, check their role (admin, editor, viewer)
  • Display appropriate permissions for each role
  • Handle unknown roles gracefully
Show Solution
<?php
$isLoggedIn = true;
$userRole = "editor";

if (!$isLoggedIn) {
    echo "Please log in to continue.\n";
} else {
    echo "Welcome! You are logged in.\n";

    if ($userRole === "admin") {
        echo "Permissions: Create, Read, Update, Delete, Manage Users\n";
    } elseif ($userRole === "editor") {
        echo "Permissions: Create, Read, Update\n";
    } elseif ($userRole === "viewer") {
        echo "Permissions: Read only\n";
    } else {
        echo "Unknown role. Please contact support.\n";
    }
}
?>

Summary

  • if: Executes code when condition is true
  • else: Executes when if condition is false
  • elseif: Checks additional conditions in sequence
  • Nested if: Place if inside another if for complex logic
  • Alternative syntax: Use if:...endif; in templates
  • Logical operators: &&, ||, ! combine conditions
  • Always use braces: Even for single statements
  • Use === over ==: For type-safe comparisons

What's Next?

Now that you understand if statements, let's explore Switch Statements - a cleaner way to handle multiple conditions when comparing a single value against many options!