← Back to PHP Course | Chapter 4: Control Flow | Lesson 1 of 14

PHP if Statement

Basic if Statement

An if statement runs its block only when the condition inside the parentheses evaluates to true; if it's false, PHP skips the entire block and moves straight to whatever comes after it — no error, no output, just silently continuing execution.

Example: Basic if Statement

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

Comparison inside Conditions

=== compares both value and type without any automatic conversion, which makes it the safer default inside an if condition — if ($status === active) won't accidentally match 1 or "1" the way the looser == operator sometimes can.

Example: Comparison inside Conditions

php
<?php
$status = "active";
if ($status === 'active') {
    echo "Status is active.";
}
?>

Logical AND (&&) in Conditions

&& inside a condition requires every joined expression to be true before the block runs — if ($age >= 18 && $hasConsent) only executes when both checks pass, which is exactly the pattern for enforcing multiple independent requirements at once.

Example: Logical AND (&&) in Conditions

php
<?php
$age = 20;
$hasConsent = true;
if ($age >= 18 && $hasConsent) {
    echo "Access granted.";
}
?>

Logical OR (||) in Conditions

|| inside a condition lets the block run if *any* one of the joined expressions is true, which suits situations with several acceptable paths to the same outcome — like accepting a login from either a username or an email address.

Example: Logical OR (||) in Conditions

php
<?php
$username = "";
$email = "[email protected]";
if ($username || $email) {
    echo "Login accepted.";
}
?>

Nested if Statements

Placing one if inside another lets you check a second condition only once the first has already passed — useful when the second check genuinely only makes sense in that context (checking a file's contents, say, only after confirming the file exists at all).

Example: Nested if Statements

php
<?php
$fileExists = true;
if ($fileExists) {
    $content = "sample data";
    if (!empty($content)) {
        echo "File exists and has content.";
    }
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.