HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP If / Else

Conditional statements are used to perform different actions based on different conditions. They are the heart of dynamic programming, allowing your website to respond differently to different users or data.


1. The if Statement

The if statement executes some code ONLY if a specified condition is true.

<?php
    $t = date("H"); // Get current hour

    if ($t < "20") {
        echo "Have a good day!";
    }
?>

2. The if...else Statement

Use the if...else statement to execute some code if a condition is true and another code if that condition is false.

<?php
    $t = date("H");

    if ($t < "20") {
        echo "Have a good day!";
    } else {
        echo "Have a good night!";
    }
?>

3. The if...elseif...else Statement

When you have more than two possible outcomes, use the elseif statement. You can have as many elseif blocks as you need.

<?php
    $t = date("H");

    if ($t < "10") {
        echo "Have a good morning!";
    } elseif ($t < "20") {
        echo "Have a good day!";
    } else {
        echo "Have a good night!";
    }
?>

4. The Ternary Operator (Shorthand if)

The ternary operator provides a way to write a simple if-else statement on a single line. It uses the ? : syntax.

<?php
    $age = 20;
    $status = ($age >= 18) ? "Adult" : "Minor";
    echo $status; // Outputs: Adult
?>
Alternative Syntax: When mixing PHP with HTML, you can use the colon syntax: if ($condition): and endif;. This makes it easier to track opening and closing brackets in large templates.
Pro Tip: Always use curly braces { } even for single lines of code. It prevents bugs when you later decide to add a second line to that block.

Key Points to Remember

  • if executes code only when a condition is true.
  • else provides a backup plan when the condition is false.
  • elseif allows you to test multiple specific conditions in sequence.
  • The Ternary Operator is great for simple, single-line logic.
  • PHP executes the first true block it finds and skips the rest.