Paramclasses Academy - Blog

Tutorials Details

Conditional Statements in PHP With Practical Examples

Conditional Statements in PHP With Practical Examples

October 9, 2026

Conditional Statements With Examples

Meta Description: Learn PHP conditional statements for beginners, including if, if-else, elseif, nested if, and switch statements with practical examples and real-world applications.

Focus Keyword: PHP Conditional Statements Tutorial

Secondary Keywords: PHP If Else, PHP Elseif Statement, PHP Nested If, PHP Switch Statement, PHP Decision Making, Core PHP Tutorial, PHP Practical Examples

Suggested URL Slug: core-php-module-4-conditional-statements

Introduction to Conditional Statements in PHP

Welcome to Module 4 of our Core PHP Programming Tutorial for Beginners.

In Module 1, we learned what PHP is and how to run a PHP program. In Module 2, we covered variables, constants, data types, comments, echo, and print. In Module 3, we learned about PHP operators, including arithmetic, assignment, comparison, logical, and ternary operators.

In this module, we will learn about conditional statements in PHP, which allow a program to make decisions based on specific conditions.

For example, a school management system can check whether a student has passed or failed. An e-commerce website can check whether a customer qualifies for a discount. A login system can verify whether a user is authorized to access a dashboard.

PHP conditional statements help developers implement these types of decision-making rules.

In this beginner-friendly tutorial, we will cover:

  • if statement

  • if-else statement

  • if-elseif-else statement

  • Nested if statement

  • switch statement

  • Real-world PHP examples

  • Common mistakes and practice exercises

Let's understand each concept step by step.

1. What Are Conditional Statements in PHP?

Conditional statements allow a program to execute different blocks of code depending on whether a condition is true or false.

For example, suppose a student must score at least 33 marks to pass an examination. PHP can compare the student's marks with the passing marks and display the appropriate result.

Simple Example

<?php
$marks = 75;

if ($marks >= 33) {
    echo "Student has passed.";
}
?>

Output:

Student has passed.

Explanation

  • $marks = 75 stores the student's marks.

  • $marks >= 33 checks whether the marks are at least 33.

  • if executes the code inside its block when the condition is true.

  • echo displays the result.

Because 75 is greater than 33, PHP displays the passing message.

Why Do We Use Conditional Statements?

Conditional statements are used to:

  1. Check whether a user is logged in.

  2. Determine whether a student has passed an examination.

  3. Apply discounts to eligible customers.

  4. Check product availability.

  5. Validate user input.

  6. Display different messages based on conditions.

  7. Control access to specific application features.

Conditional statements are a fundamental part of PHP programming and are used in almost every dynamic web application.

2. The if Statement in PHP

The if statement executes a block of code only when a specified condition evaluates to true.

Syntax

if (condition) {
    // Code executes when the condition is true
}

Example 1: Check Voting Eligibility

<?php
$age = 20;

if ($age >= 18) {
    echo "You are eligible to vote.";
}
?>

Output:

You are eligible to vote.

Explanation

The condition $age >= 18 checks whether the person's age is at least 18.

Since the age is 20, the condition is true, and PHP executes the statement inside the if block.

If the age were 16, the condition would be false, and nothing would be displayed.

Example 2: Check Product Stock

<?php
$stock = 10;

if ($stock > 0) {
    echo "Product is available.";
}
?>

Output:

Product is available.

Real-World Example: Display a Welcome Message

Suppose a website displays a welcome message only when a user is logged in.

<?php
$isLoggedIn = true;

if ($isLoggedIn) {
    echo "Welcome to your dashboard!";
}
?>

Output:

Welcome to your dashboard!

Real-world application: The if statement is useful for checking account status, product availability, membership eligibility, and other conditions in PHP applications.

Note that this example demonstrates the decision logic only. Real authentication must be implemented using secure server-side session handling and proper authorization checks.

3. The if-else Statement in PHP

The if-else statement allows a program to choose between two alternatives.

  • If the condition is true, the if block executes.

  • If the condition is false, the else block executes.

Syntax

if (condition) {
    // Executes when the condition is true
} else {
    // Executes when the condition is false
}

Example 1: Student Pass or Fail

<?php
$marks = 28;

if ($marks >= 33) {
    echo "Student has passed.";
} else {
    echo "Student has failed.";
}
?>

Output:

Student has failed.

Explanation

The program checks whether the student's marks are at least 33.

Since the student scored 28, the condition is false, and the else block executes.

Example 2: Check Even or Odd Number

<?php
$number = 7;

if ($number % 2 == 0) {
    echo "The number is even.";
} else {
    echo "The number is odd.";
}
?>

Output:

The number is odd.

The modulus operator % returns the remainder after division. An integer is even when its remainder after division by 2 is zero.

Real-World Example: Free Delivery

Suppose an online store offers free delivery when the order amount is ₹1,000 or more.

<?php
$orderAmount = 1200;

if ($orderAmount >= 1000) {
    echo "Congratulations! You qualify for free delivery.";
} else {
    echo "Delivery charges will apply.";
}
?>

Output:

Congratulations! You qualify for free delivery.

Real-world application: The if-else statement is commonly used for discounts, shipping eligibility, payment status messages, exam results, and simple access decisions.

4. The if-elseif-else Statement in PHP

The if-elseif-else statement is used when a program must check multiple conditions.

PHP evaluates the conditions from top to bottom. The first condition that evaluates to true has its block executed. If none is true, the else block executes, if present.

Syntax

if (condition1) {
    // First condition
} elseif (condition2) {
    // Second condition
} elseif (condition3) {
    // Third condition
} else {
    // No condition matched
}

Example 1: Student Grade Calculator

<?php
$marks = 85;

if ($marks >= 90) {
    echo "Grade A+";
} elseif ($marks >= 80) {
    echo "Grade A";
} elseif ($marks >= 70) {
    echo "Grade B";
} elseif ($marks >= 60) {
    echo "Grade C";
} elseif ($marks >= 33) {
    echo "Grade D";
} else {
    echo "Fail";
}
?>

Output:

Grade A

Explanation

  • Marks of 90 or above receive Grade A+.

  • Marks of 80 or above receive Grade A if the earlier condition did not match.

  • Marks of 70 or above receive Grade B if the earlier conditions did not match.

  • Marks of 60 or above receive Grade C.

  • Marks of 33 or above receive Grade D.

  • Lower marks result in Fail.

The order of conditions matters. If you check $marks >= 60 before $marks >= 90, a student scoring 95 could receive the wrong grade because the earlier condition would already be true.

Example 2: Age Category

<?php
$age = 25;

if ($age < 13) {
    echo "Child";
} elseif ($age < 20) {
    echo "Teenager";
} elseif ($age < 60) {
    echo "Adult";
} else {
    echo "Senior";
}
?>

Output:

Adult

Real-World Example: Employee Bonus Calculation

Suppose a company provides bonuses based on employee performance scores.

<?php
$performanceScore = 92;

if ($performanceScore >= 90) {
    echo "Bonus: 20%";
} elseif ($performanceScore >= 75) {
    echo "Bonus: 10%";
} elseif ($performanceScore >= 60) {
    echo "Bonus: 5%";
} else {
    echo "No bonus";
}
?>

Output:

Bonus: 20%

Real-world application: Multiple-condition statements are useful for grade calculations, pricing tiers, membership categories, employee performance rules, and discount levels.

The percentages in this example are illustrative. Real bonus calculations should follow the organization's actual policy.

5. Nested if Statements in PHP

A nested if statement is an if statement placed inside another if statement.

Nested conditions are useful when one decision depends on another decision.

Syntax

if (condition1) {
    if (condition2) {
        // Executes when both conditions are true
    }
}

Example 1: Check Login and Admin Status

<?php
$isLoggedIn = true;
$isAdmin = true;

if ($isLoggedIn) {
    if ($isAdmin) {
        echo "Welcome, Administrator!";
    } else {
        echo "Welcome, User!";
    }
} else {
    echo "Please log in first.";
}
?>

Output:

Welcome, Administrator!

Explanation

  1. The outer if checks whether the user is logged in.

  2. If the user is logged in, the inner if checks whether the user is an administrator.

  3. PHP displays the appropriate message based on both values.

Example 2: Check Product Availability and Stock

<?php
$productExists = true;
$stock = 5;

if ($productExists) {
    if ($stock > 0) {
        echo "Product is available for purchase.";
    } else {
        echo "Product is currently out of stock.";
    }
} else {
    echo "Product not found.";
}
?>

Output:

Product is available for purchase.

Real-World Example: Online Shopping Checkout

Before allowing a checkout process to continue, an application might need to check that a product exists and that enough stock is available.

Nested conditions can represent this flow in a beginner-level example.

In a real application, product existence, stock quantities, prices, and order creation must be verified on the server. Stock should also be checked and reserved safely when the order is processed.

Real-world application: Nested if statements are useful when a second decision depends on the result of a first decision, such as multi-step validation, order processing, and role-based workflows.

6. The switch Statement in PHP

The switch statement is used to select one block of code from several alternatives based on the value of an expression.

It can make code easier to read when one variable is compared against several fixed options.

Syntax

switch ($variable) {
    case "value1":
        // Code for value1
        break;

    case "value2":
        // Code for value2
        break;

    default:
        // Code when no case matches
}

Important Keywords

  • switch evaluates the expression.

  • case defines a possible matching value.

  • break exits the switch block.

  • default provides a fallback when no case matches.

Example 1: Display Day Name

<?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;

    default:
        echo "Weekend or invalid day";
}
?>

Output:

Wednesday

Explanation

The variable $day contains the value 3.

PHP matches it to case 3, displays Wednesday, and exits the switch statement because of break.

If no case matches, the default block runs.

Example 2: Simple Calculator Using switch

<?php
$a = 20;
$b = 10;
$operator = "+";

switch ($operator) {
    case "+":
        echo $a + $b;
        break;

    case "-":
        echo $a - $b;
        break;

    case "*":
        echo $a * $b;
        break;

    case "/":
        if ($b != 0) {
            echo $a / $b;
        } else {
            echo "Cannot divide by zero.";
        }
        break;

    default:
        echo "Invalid operator.";
}
?>

Output:

30

Real-World Example: Order Status

An e-commerce website may display different messages based on the current order status.

<?php
$status = "shipped";

switch ($status) {
    case "pending":
        echo "Your order is being processed.";
        break;

    case "shipped":
        echo "Your order has been shipped.";
        break;

    case "delivered":
        echo "Your order has been delivered.";
        break;

    case "cancelled":
        echo "Your order has been cancelled.";
        break;

    default:
        echo "Order status is unavailable.";
}
?>

Output:

Your order has been shipped.

Real-world application: The switch statement is useful for handling order statuses, menu choices, payment statuses, selected options, and other fixed-value decisions.

7. Difference Between if-else and switch in PHP

Both if-else and switch allow a program to choose between different code paths, but they are suited to different situations.

if-else switch
Can evaluate complex conditions. Convenient for matching an expression against fixed cases.
Supports comparisons such as >, <, and >=. Commonly used for selecting among specific values.
Useful for ranges and multiple logical conditions. Useful for menus, statuses, and predefined choices.
Can be used for almost any boolean condition. Uses case labels to select a matching branch.

Example: if-else

<?php
$marks = 75;

if ($marks >= 80) {
    echo "Excellent";
} elseif ($marks >= 60) {
    echo "Good";
} else {
    echo "Needs Improvement";
}
?>

Example: switch

<?php
$role = "editor";

switch ($role) {
    case "admin":
        echo "Administrator";
        break;

    case "editor":
        echo "Content Editor";
        break;

    case "user":
        echo "Regular User";
        break;

    default:
        echo "Unknown Role";
}
?>

Best practice: Use if-elseif-else when conditions involve ranges or logical expressions. Use switch when selecting among several known values.

8. Real-World Practical Example: Login Form Validation

Suppose you are developing a basic login form. Before checking a user's credentials against a database, PHP can validate whether the submitted fields are empty.

The following example demonstrates only basic server-side input validation, not complete authentication.

<?php
$username = "rahul";
$password = "";

if (empty($username) && empty($password)) {
    echo "Please enter your username and password.";
} elseif (empty($username)) {
    echo "Please enter your username.";
} elseif (empty($password)) {
    echo "Please enter your password.";
} else {
    echo "Input received. Credentials must now be verified.";
}
?>

Output:

Please enter your password.

Explanation

  • empty() checks whether a value is empty or evaluates as empty under PHP's rules.

  • The first condition checks whether both fields are empty.

  • The next conditions check each field separately.

  • The final branch indicates that input has been received.

Important security note: A real login system must verify credentials against stored password hashes using password_verify(), use secure session handling, and enforce authorization on the server. A hard-coded username or password check is not sufficient for production authentication.

9. Real-World Practical Example: Discount Eligibility

Let's create a practical discount example for an online shopping website.

Suppose a store offers discounts based on the order amount:

  • ₹5,000 or more: 20% discount

  • ₹3,000 or more: 10% discount

  • ₹1,000 or more: 5% discount

  • Below ₹1,000: no discount

<?php
$orderAmount = 4000;
$discount = 0;

if ($orderAmount >= 5000) {
    $discount = 20;
} elseif ($orderAmount >= 3000) {
    $discount = 10;
} elseif ($orderAmount >= 1000) {
    $discount = 5;
} else {
    $discount = 0;
}

$discountAmount = $orderAmount * $discount / 100;
$finalAmount = $orderAmount - $discountAmount;

echo "<h2>Shopping Discount</h2>";
echo "Order Amount: ₹" . $orderAmount . "<br>";
echo "Discount: " . $discount . "%<br>";
echo "Discount Amount: ₹" . $discountAmount . "<br>";
echo "Final Amount: ₹" . $finalAmount;
?>

Output:

Shopping Discount

Order Amount: ₹4000
Discount: 10%
Discount Amount: ₹400
Final Amount: ₹3600

How Does This Program Work?

  1. The program stores the order amount.

  2. The if-elseif-else statement determines the applicable discount.

  3. Arithmetic operators calculate the discount amount.

  4. The program subtracts the discount from the original order amount.

  5. echo displays the final bill.

Real-world application: This logic can be extended to coupon systems, loyalty programs, promotional campaigns, and e-commerce checkout pages.

For a production system, validate the order amount on the server and use reliable monetary calculations.

10. Common Mistakes Beginners Should Avoid

When learning PHP conditional statements, beginners should watch out for these common errors.

Mistake 1: Using Assignment Instead of Comparison

Incorrect for checking equality:

if ($age = 18) {
    echo "Age is 18";
}

This assigns 18 to $age rather than comparing the existing value.

Correct:

if ($age == 18) {
    echo "Age is 18";
}

When you need both value and type to match, consider ===.

Mistake 2: Forgetting Curly Braces

Curly braces make it clear which statements belong to a conditional block.

if ($marks >= 33) {
    echo "Pass";
    echo "Congratulations!";
}

Both statements execute when the condition is true.

Mistake 3: Incorrect Order of Conditions

if ($marks >= 33) {
    echo "Pass";
} elseif ($marks >= 80) {
    echo "Excellent";
}

A student scoring 90 receives Pass because the first condition is already true.

Put the more specific or higher threshold first:

if ($marks >= 80) {
    echo "Excellent";
} elseif ($marks >= 33) {
    echo "Pass";
} else {
    echo "Fail";
}

Mistake 4: Forgetting break in switch

Without break, PHP may continue executing subsequent case statements after a match. This behavior is called fall-through.

Add break when you want execution to stop after a case.

Mistake 5: Using Too Many Nested Conditions

Deeply nested conditions can become difficult to understand. Consider simplifying the logic or using elseif when it improves readability.

Mistake 6: Trusting User Input

Never assume that data submitted by a browser is valid or trustworthy. Validate it on the server before making important decisions, processing payments, or changing database records.

11. Practice Exercises for Beginners

Try the following exercises to strengthen your understanding of PHP conditional statements.

Exercise 1: Check Positive or Negative Number

Create a variable and use if-else to check whether the number is positive or negative. Also consider the case where it is zero.

Exercise 2: Student Pass or Fail

Create a variable named $marks. Display Pass if the marks are at least 33; otherwise, display Fail.

Exercise 3: Grade Calculator

Use if-elseif-else to assign grades based on marks.

Exercise 4: Voting Eligibility

Check whether a person's age meets the eligibility threshold.

Exercise 5: Even or Odd

Use the modulus operator and if-else to determine whether a number is even or odd.

Exercise 6: Product Availability

Create a variable named $stock. Display In Stock when the quantity is greater than zero; otherwise, display Out of Stock.

Exercise 7: Simple Calculator

Use switch to perform addition, subtraction, multiplication, or division.

Exercise 8: Employee Bonus

Calculate an employee bonus based on a performance score.

Exercise 9: Discount Calculator

Apply different discounts based on an order's total value.

Exercise 10: Login Form Validation

Use conditional statements to check whether a username and password field have been supplied. Do not store or display real passwords in plain text.

12. Frequently Asked Questions About PHP Conditional Statements

What are conditional statements in PHP?

Conditional statements execute different blocks of code based on whether specified conditions evaluate to true or false.

What is the difference between if and if-else in PHP?

The if statement executes code only when its condition is true. The if-else statement provides an alternative block that executes when the condition is false.

What is an elseif statement in PHP?

The elseif statement checks another condition when the preceding if or elseif condition was false.

What is a nested if statement?

A nested if is an if statement inside another conditional block. It is useful when one decision depends on another.

What is the switch statement used for in PHP?

The switch statement selects a block of code based on a matching value. It is useful for order statuses, menus, and predefined options.

Can I use multiple conditions in a PHP if statement?

Yes. Logical operators such as && and || can combine conditions.

Which is better: if-else or switch?

Neither is universally better. Use if-elseif-else for ranges and complex conditions. Use switch for selecting among fixed values.

Are conditional statements important in real-world PHP projects?

Yes. They are essential for validation, authentication logic, pricing rules, order processing, result calculations, and many other application features.

Conclusion

In this Core PHP Module 4 tutorial, we learned about the if, if-else, if-elseif-else, nested if, and switch statements with beginner-friendly examples.

We also explored practical applications such as student results, product availability, login form validation, and shopping discounts.

Conditional statements help PHP programs make decisions based on changing data and business requirements. Once you understand them, you can build more interactive and useful web applications.

Practice each example yourself, change the variable values, and observe how the output changes.