PHP Conditional Statements - Codingque

PHP Conditional Statements

Understand how to use if, else, and switch case statements in PHP with examples and explanations.

Introduction to Conditional Statements

Conditional statements in PHP are used to perform different actions based on different conditions. The most commonly used conditional statements are if, else, and switch.

1. if and else Statements

The if statement allows you to execute a block of code if a specified condition is true. The else statement provides an alternative block of code to execute if the condition is false.

<?php
$age = 20;

if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are not an adult.";
}
?>

Explanation: The if statement checks if the value of $age is greater than or equal to 18. If true, it prints "You are an adult." If false, the else block prints "You are not an adult."

Nested if Statements

Nested if statements are if statements inside other if statements:

<?php
$age = 20;
$hasID = true;

if ($age >= 18) {
    if ($hasID) {
        echo "You are an adult with an ID.";
    } else {
        echo "You are an adult but no ID.";
    }
} else {
    echo "You are not an adult.";
}
?>

Explanation: The outer if checks if $age is greater than or equal to 18. If true, it further checks if $hasID is true. Based on these conditions, it prints different messages.

2. switch Case Statement

The switch statement is used to select one of many code blocks to execute. It is often used as a cleaner alternative to multiple if statements when dealing with many conditions.

<?php
$day = 3;

switch ($day) {
    case 1:
        echo "Monday";
        break;
    case 2:
        echo "Tuesday";
        break;
    case 3:
        echo "Wednesday";
        break;
    case 4:
        echo "Thursday";
        break;
    case 5:
        echo "Friday";
        break;
    case 6:
        echo "Saturday";
        break;
    case 7:
        echo "Sunday";
        break;
    default:
        echo "Invalid day";
}
?>

Explanation: The switch statement evaluates the value of $day. Based on the value, it matches one of the case labels and executes the corresponding block of code. The default case is used if none of the case values match.

Previous Next
Modern Footer