Autocodewizard Logo Conditional Statements - Autocodewizard Ebooks - PHP Essentials: Building Dynamic Web Applications

Chapter 4: Conditional Statements

Master conditional statements like if, elseif, and else to control the flow of your PHP code based on conditions.

In this chapter, we’ll explore conditional statements in PHP. Conditional statements enable you to control the flow of your code by making decisions based on certain conditions. Understanding these statements is essential for building dynamic and responsive applications.

The if Statement

The if statement executes a block of code if a specified condition is true. Here’s the basic syntax:

<?php
$age = 20;

if ($age >= 18) {
    echo "You are eligible to vote.";
}
?>

In this example, the message "You are eligible to vote." is displayed only if $age is 18 or greater.

The else Statement

The else statement can be used alongside if to execute code if the condition is false:

<?php
$age = 16;

if ($age >= 18) {
    echo "You are eligible to vote.";
} else {
    echo "You are not eligible to vote.";
}
?>

Here, "You are not eligible to vote." is displayed if $age is less than 18.

The elseif Statement

The elseif statement allows you to add multiple conditions. Each condition is evaluated in sequence until one is found to be true:

<?php
$score = 85;

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

In this example, the code assigns a grade based on the $score value, checking each condition in sequence.

The Ternary Operator

The ternary operator is a shorthand way to write if...else statements. It has the syntax condition ? value_if_true : value_if_false:

<?php
$isMember = true;
$discount = $isMember ? 10 : 0;
echo "Discount: " . $discount . "%";
?>

In this example, $discount is set to 10 if $isMember is true, and 0 otherwise.

The switch Statement

The switch statement is used to execute different code blocks based on the value of a variable. It’s often used when you have multiple possible values to check:

<?php
$day = "Wednesday";

switch ($day) {
    case "Monday":
        echo "Start of the work week!";
        break;
    case "Wednesday":
        echo "Midweek day!";
        break;
    case "Friday":
        echo "Almost the weekend!";
        break;
    default:
        echo "Have a good day!";
}
?>

In this example, "Midweek day!" is displayed because $day is set to "Wednesday". The default case is executed if none of the conditions match.

Summary and Next Steps

In this chapter, we covered conditional statements in PHP, including if, elseif, else, the ternary operator, and the switch statement. These tools allow you to control the flow of your code based on different conditions. In the next chapter, we’ll learn about loops in PHP, which enable you to repeat tasks and iterate over data collections.