Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Conditional Statements in PHP

Introduction

Conditional statements are an essential part of any programming language. They allow you to execute different code blocks based on certain conditions. In PHP, there are several types of conditional statements:

  • if statement
  • if-else statement
  • if-elseif-else statement
  • switch statement

if Statement

The if statement executes a block of code if a specified condition is true. The syntax is as follows:

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

Example:

<?php
$a = 10;
if ($a > 5) {
    echo "a is greater than 5";
}
?>
Output: a is greater than 5

if-else Statement

The if-else statement executes one block of code if a condition is true and another block of code if the condition is false. The syntax is as follows:

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

Example:

<?php
$a = 10;
if ($a > 15) {
    echo "a is greater than 15";
} else {
    echo "a is not greater than 15";
}
?>
Output: a is not greater than 15

if-elseif-else Statement

The if-elseif-else statement allows you to test multiple conditions and execute different code blocks based on which condition is true. The syntax is as follows:

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 neither condition1 nor condition2 is true
}

Example:

<?php
$a = 10;
if ($a > 15) {
    echo "a is greater than 15";
} elseif ($a == 10) {
    echo "a is equal to 10";
} else {
    echo "a is less than 10";
}
?>
Output: a is equal to 10

switch Statement

The switch statement is used to perform different actions based on different conditions. It is often used as an alternative to the if-elseif-else statement. The syntax is as follows:

switch (expression) {
    case value1:
        // code to be executed if expression == value1
        break;
    case value2:
        // code to be executed if expression == value2
        break;
    default:
        // code to be executed if expression doesn't match any case
}

Example:

<?php
$day = "Tuesday";
switch ($day) {
    case "Monday":
        echo "Today is Monday";
        break;
    case "Tuesday":
        echo "Today is Tuesday";
        break;
    case "Wednesday":
        echo "Today is Wednesday";
        break;
    default:
        echo "Today is not Monday, Tuesday or Wednesday";
}
?>
Output: Today is Tuesday