What are control structures? Explain types of if conditional statement in PHP

May 7, 2023 · Team EasyExamNotes · 2 min read (est.) · 0 comments

Share on WhatsApp

Control structures are programming constructs that determine the flow of execution of a program. In PHP, there are several types of control structures, including conditional statements, loops, and function calls.

The if conditional statement is used in PHP to execute code based on whether a condition is true or false. There are several types of if conditional statements in PHP, including:

1. if statement:

The simplest type of if statement checks a single condition and executes code if it is true. Here is an example:

$age = 25;
if ($age >= 18) {
    echo "You are old enough to vote";
}

2. if-else statement:

This type of if statement checks a single condition and executes one set of code if it is true, and a different set of code if it is false. Here is an example:

$age = 16;
if ($age >= 18) {
    echo "You are old enough to vote";
} else {
    echo "You are not old enough to vote";
}

3. if-elseif-else statement:

This type of if statement checks multiple conditions in a chain, and executes different code based on which condition is true.

Here is an example:

$grade = 85;
if ($grade >= 90) {
    echo "You got an A!";
} elseif ($grade >= 80) {
    echo "You got a B!";
} elseif ($grade >= 70) {
    echo "You got a C!";
} else {
    echo "You did not pass";
}

4. nested if statement:

This type of if statement includes an if statement within another if statement. It is used when more than one condition needs to be checked.

Here is an example:

$age = 25;
$gender = "male";
if ($age >= 18) {
    if ($gender == "male") {
        echo "You are an adult male";
    } elseif ($gender == "female") {
        echo "You are an adult female";
    }
} else {
    echo "You are not an adult";
}

Discussion

Ask a question, share your thoughts or report an error.

Sign in to participate in the discussion.

Join the discussion