PHP If Else and Elseif

Conditional statements control the flow of a PHP script based on whether specific conditions are true or false. Rather than running every line of code from top to bottom without exception, conditional statements allow a script to take different paths depending on the data it receives. This is what makes PHP programs dynamic and intelligent.

The if Statement

The simplest conditional structure checks whether a condition is true. If it is, the code inside the block runs. If not, the block is skipped entirely.

<?php
  $temperature = 32;

  if ($temperature <= 0) {
    echo "It is freezing outside.";
  }
?>

In this example, the message appears only when the temperature is 0 or below. If $temperature is 32, the block is skipped and nothing is output.

The if-else Statement

The else clause provides an alternative path when the condition is false. Exactly one of the two blocks will always run.

<?php
  $age = 16;

  if ($age >= 18) {
    echo "Eligible to vote.";
  } else {
    echo "Not eligible to vote yet.";
  }

  // Outputs: Not eligible to vote yet.
?>

The if-elseif-else Statement

When there are more than two possible outcomes, elseif adds additional conditions to check. PHP evaluates each condition from top to bottom and runs the first block where the condition is true. If none of the conditions match, the else block runs.

<?php
  $score = 74;

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

  // Outputs: Grade: C
?>

PHP stops checking as soon as it finds a true condition. Even if later conditions would also be true, they are not evaluated.

Nested if Statements

An if statement can be placed inside another if statement. This is called nesting.

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

  if ($isLoggedIn) {
    echo "Welcome back!";

    if ($isAdmin) {
      echo " You have admin access.";
    } else {
      echo " You have standard access.";
    }
  } else {
    echo "Please log in first.";
  }

  // Outputs: Welcome back! You have standard access.
?>

Nesting should be kept shallow when possible. Too many levels of nesting makes code hard to read and maintain.

Combining Conditions with Logical Operators

<?php
  $username = "alice";
  $password = "secure123";

  if ($username === "alice" && $password === "secure123") {
    echo "Login successful.";
  } else {
    echo "Invalid credentials.";
  }

  $day = "Saturday";

  if ($day === "Saturday" || $day === "Sunday") {
    echo "It is the weekend.";
  } else {
    echo "It is a weekday.";
  }
?>

The Ternary Operator

The ternary operator is a compact way to write a simple if-else statement in a single line. It takes the form: condition ? value_if_true : value_if_false.

<?php
  $stock = 0;
  $status = ($stock > 0) ? "In Stock" : "Out of Stock";

  echo $status;   // Outputs: Out of Stock
?>

This is equivalent to:

<?php
  $stock = 0;

  if ($stock > 0) {
    $status = "In Stock";
  } else {
    $status = "Out of Stock";
  }

  echo $status;
?>

Use the ternary operator for simple assignments. For complex logic, standard if-else is easier to read.

Null Coalescing as a Conditional Shorthand

The ?? operator is a concise way to provide fallback values when a variable might not be set.

<?php
  $userInput = $_POST['name'] ?? "Anonymous";
  echo "Hello, " . $userInput;

  // If $_POST['name'] is not set, outputs: Hello, Anonymous
?>

Truthy and Falsy Values in PHP

PHP does not require strict boolean values in conditions. Many values are automatically evaluated as either truthy or falsy.

Values that evaluate as false (falsy):

  • false
  • 0 (integer zero)
  • 0.0 (float zero)
  • "" (empty string)
  • "0" (string containing zero)
  • [] (empty array)
  • null

Everything else evaluates as true.

<?php
  $items = [];

  if ($items) {
    echo "There are items.";
  } else {
    echo "No items found.";   // Outputs this - empty array is falsy
  }

  $count = 5;

  if ($count) {
    echo "Count is non-zero.";   // Outputs this - 5 is truthy
  }
?>

Alternative Syntax for if Statements

PHP supports an alternative syntax that is often used in template files where PHP is mixed with HTML.

<?php $isSubscribed = true; ?>

<?php if ($isSubscribed): ?>
  <p>Thank you for subscribing!</p>
<?php else: ?>
  <p>Please subscribe to continue.</p>
<?php endif; ?>

Instead of curly braces, this syntax uses a colon after the condition and endif; to close the block. It is cleaner when embedding PHP inside HTML markup.

Key Points

  • The if statement runs a block of code when a condition is true.
  • The else block runs when the condition is false.
  • Multiple conditions are handled with elseif.
  • Conditions are evaluated top to bottom; the first true condition wins.
  • The ternary operator (? :) condenses simple if-else into one line.
  • The null coalescing operator (??) provides fallback values for potentially unset variables.
  • PHP uses truthy/falsy evaluation — empty arrays, zero, and null all count as false in conditions.

Leave a Comment

Your email address will not be published. Required fields are marked *