BCA SCHOOL
Programming Tutorials • Notes • Practical • Books
LATEST TUTORIALS

CONDITIONAL STRUCTURE | BCA SEM 02 PHP BKNMU JUNAGADH

by BCA School •
Conditional Structures in PHP

Conditional Structures in PHP

In PHP, Conditional Structures are constructs that allow developers to execute specific blocks of code based on whether a condition is true or false. These structures are essential for decision-making within a program.

Definition

A Conditional Structure in PHP evaluates a given condition (usually a logical expression) and performs different actions depending on whether the condition evaluates to true or false.

Types of Conditional Structures in PHP

if Statement

Executes a block of code if the condition is true.

if (condition) {
    // Code to be executed if condition is true
}

Example:
$number = 10;

if ($number > 5) {
    echo "The number is greater than 5.";
}

if-else Statement

Provides an alternative block of code to execute if the condition is false.

if (condition) {
    // Code to be executed if condition is true
} else {
    // Code to be executed if condition is false
}

Example:
$number = 3;

if ($number > 5) {
    echo "The number is greater than 5.";
} else {
    echo "The number is not greater than 5.";
}

if-elseif-else Statement

Allows checking multiple conditions sequentially.

if (condition1) {
    // Code to be executed if condition1 is true
} elseif (condition2) {
    // Code to be executed if condition2 is true
} else {
    // Code to be executed if none of the conditions are true
}

Example:
$number = 5;

if ($number > 10) {
    echo "The number is greater than 10.";
} elseif ($number == 5) {
    echo "The number is exactly 5.";
} else {
    echo "The number is less than 10 and not 5.";
}

Switch Statement

A more efficient way to evaluate a variable against multiple values.

switch (variable) {
    case value1:
        // Code to execute if variable equals value1
        break;
    case value2:
        // Code to execute if variable equals value2
        break;
    default:
        // Code to execute if no cases match
}

Example:
$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 "Just another day.";
}