"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Conditional Statements (if, else, elseif, switch)

 

Conditional statements in PHP allow you to make decisions in your code based on certain conditions. They enable your scripts to execute different blocks of code depending on whether a condition evaluates to true or false.


If Statement

The if statement executes a block of code if a specified condition is true.

Example:

<?php

$age = 20;

 

if ($age >= 18) {

    echo "You are an adult.";

}

?>

Output:

You are an adult.


Else Statement

The else statement executes a block of code if the if condition is false.

Example:

<?php

$age = 15;

 

if ($age >= 18) {

    echo "You are an adult.";

} else {

    echo "You are a minor.";

}

?>

Output:

You are a minor.


Elseif Statement

The elseif statement allows you to check multiple conditions.

Example:

<?php

$score = 75;

 

if ($score >= 90) {

    echo "Grade: A";

} elseif ($score >= 75) {

    echo "Grade: B";

} elseif ($score >= 50) {

    echo "Grade: C";

} else {

    echo "Grade: F";

}

?>

Output:

Grade: B


Switch Statement

The switch statement is an alternative to multiple elseif statements. It compares a value against multiple cases and executes the matching block.

Example:

<?php

$day = "Tuesday";

 

switch ($day) {

    case "Monday":

        echo "Start of the week";

        break;

    case "Tuesday":

        echo "Second day of the week";

        break;

    case "Friday":

        echo "Last working day";

        break;

    default:

        echo "Midweek days";

}

?>

Output:

Second day of the week

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)