If-Else Statements in PHP: A Complete Guide for Beginners
if-else statements in PHP with examples
Control flow is one of the most important concepts in any programming language. In PHP, if-else statements help you execute different blocks of code based on specific conditions. Whether you're validating form input, controlling user access, or performing logical checks, the if-else structure is essential.
This article explains if, else, elseif, nested if statements, and real PHP examples to help beginners master conditional logic.
If-else statements allow PHP to make decisions. They evaluate a condition and execute code only when that condition is true.
In simple words:
if = run code when a condition is true
else = run code when the condition is false
elseif = run code when additional conditions are true
<?php
if (condition) {
// Code to execute if condition is true
}
?>
<?php
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
?>
Used when you want one block of code to run if the condition is true, and another if it is false.
<?php
if (condition) {
// Executes if condition is true
} else {
// Executes if condition is false
}
?>
<?php
$number = 5;
if ($number % 2 == 0) {
echo "Even Number";
} else {
echo "Odd Number";
}
?>
Useful for checking multiple conditions.
<?php
if (condition1) {
// Code for condition1
} elseif (condition2) {
// Code for condition2
} else {
// Default code
}
?>
<?php
$marks = 75;
if ($marks >= 90) {
echo "Grade A";
} elseif ($marks >= 75) {
echo "Grade B";
} elseif ($marks >= 50) {
echo "Grade C";
} else {
echo "Fail";
}
?>
An if statement inside another if.
<?php
$age = 20;
$citizen = true;
if ($age >= 18) {
if ($citizen) {
echo "You are eligible to vote.";
}
}
?>
<?php
$age = 25;
$hasLicense = true;
if ($age >= 18 && $hasLicense) {
echo "You can drive";
}
?>
<?php
$username = "admin";
$password = "12345";
if ($username == "admin" && $password == "12345") {
echo "Login Successful";
} else {
echo "Invalid Credentials";
}
?>
❌ Missing curly braces { }
❌ Using = instead of == for comparison
❌ Unnecessary semicolon after if condition
❌ Writing unreachable else blocks
Example mistake:
if ($a == 10); // ❌ Wrong: Semicolon ends the if
{
echo "Always runs";
}
Correct:
if ($a == 10) {
echo "Runs only if true";
}
If-else statements are the backbone of decision-making in PHP. They help you control the flow of execution and build dynamic, intelligent applications. Once you master basic and nested conditions, you'll be ready to work with loops, functions, and more complex logic.