LessonsPHP Basics → Lesson 4

If / Else Conditions

PHP
⏱ 15 min read 📖 Beginner Not completed

Conditions allow your PHP code to make decisions. If something is true, do one thing — otherwise, do another. This is one of the most important concepts in programming.

Basic if statement

The simplest form — run code only if a condition is true:

PHP
<?php

$age = 20;

if ($age >= 18) {
    echo "You are an adult.";
}

// Output: You are an adult.
?>

if / else

Add an else block to handle the case when the condition is false:

PHP
<?php

$score = 65;

if ($score >= 70) {
    echo "Pass!";
} else {
    echo "Fail. Try again.";
}

// Output: Fail. Try again.
?>

if / elseif / else

Check multiple conditions using elseif:

PHP
<?php

$score = 85;

if ($score >= 90) {
    echo "Grade: A";
} elseif ($score >= 80) {
    echo "Grade: B";
} elseif ($score >= 70) {
    echo "Grade: C";
} else {
    echo "Grade: F";
}

// Output: Grade: B
?>

Comparison Operators

OperatorMeaningExample
==Equal to$a == $b
===Identical (same type)$a === $b
!=Not equal$a != $b
>Greater than$a > $b
<Less than$a < $b
>=Greater than or equal$a >= $b

Ternary Operator (shorthand)

A one-line shortcut for simple if/else:

PHP
<?php

$age = 20;

// Longhand
if ($age >= 18) {
    $status = "adult";
} else {
    $status = "minor";
}

// Shorthand (ternary)
$status = ($age >= 18) ? "adult" : "minor";

echo $status; // adult
?>
💡
Pro tip: Always use === (triple equals) instead of == (double equals) when you want to check both value AND type. This prevents unexpected bugs in PHP.
← Previous Lesson Next Lesson →
🧠

Ready to test your knowledge?

Take the quiz for this lesson to reinforce what you learned about conditions.

Take Quiz →