PHP Conditionals

if Statement

Basic Structure

if (condition) {
    // code to execute if condition is true
}

Example

$score = 85;

if ($score > 80) {
  echo "Great job!";
}

Runs the block if the condition is true.

if-else Statement

$grade = 38;

if ($grade >= 50) {
  echo "Pass";
} else {
  echo "Fail";
}

if-elseif-else Statement

$grade = 75;

if ($grade >= 90) {
  echo "A";
} elseif ($grade >= 80) {
  echo "B";
} elseif ($grade >= 70) {
  echo "C";
} else {
  echo "Fail";
}

Nested if Statements

$temp = 25;

if ($temp > 0) {
  if ($temp < 30) {
    echo "Nice weather";
  }
}

You can place if blocks inside each other.

Ternary Operator

The ternary operator is a shorthand way of writing an if-else statement on a single line. It checks a condition and returns one of two values depending on whether the condition is true or false.

Syntax:

condition ? value_if_true : value_if_false;

Example:

$loggedIn = true;
echo $loggedIn ? "Welcome!" : "Please log in.";

This is equivalent to:

if ($loggedIn) {
  echo "Welcome!";
} else {
  echo "Please log in.";
}

Since $loggedIn is true, it prints "Welcome!". If it were false, it would print "Please log in."

Best Practice: Use the ternary operator for simple conditional assignments or outputs. Use a full if-else block for more complex logic.

switch Statement

A switch statement allows you to compare the value of a variable against multiple possible values (called "cases") and execute a block of code based on the first match. It's often cleaner and more readable than writing several if-else statements in a row.

Syntax:

switch (variable) {
case value1:
  // code to execute if variable == value1
  break;
case value2:
  // code to execute if variable == value2
  break;
...
default:
  // code to execute if no case matches
}

Example:

$color = "green";

switch ($color) {
  case "red":
    echo "Stop";
    break;
  case "green":
    echo "Go";
    break;
  case "yellow":
    echo "Wait";
    break;
  default:
    echo "Invalid color";
}

In this example, the value of $color is compared to each case. Since it's "green", the message "Go" is printed. If none of the cases match, the default block runs.

  • break exits the switch block to prevent "fall-through" to other cases.
  • default acts as a fallback if no case matches. It's optional but recommended.

Best Practice: Always include break in each case unless you intentionally want multiple cases to share the same logic.

Best Practices

  • Use curly braces even for single-line blocks
  • Use `switch` for cleaner multi-condition comparisons
  • Use `===` to avoid unexpected type coercion

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic