← Back to Chapters

PHP If Statement

? PHP If Statement

? Quick Overview

The if statement in PHP is used to execute code only when a specified condition evaluates to true. It plays a critical role in decision-making and controlling the flow of a PHP program.

? Key Concepts

  • Conditions are evaluated as true or false
  • Comparison operators are commonly used inside conditions
  • Multiple conditions can be chained using elseif and else
  • Nested if statements allow complex decision logic

? Syntax / Theory

The PHP if statement checks a condition and executes the block of code only if that condition is satisfied. If the condition is false, the code inside the block is skipped.

? Logic Playground (Interactive)

Test the logic: Enter a numeric Score (0-100) to see the if...elseif logic in action.

Result will appear here...

This simulates how PHP would evaluate your input based on score thresholds.

? Basic If Statement

? View Code Example
// Check if the user is eligible to vote
<?php
$age = 20;

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

? If...Else Statement

? View Code Example
// Decide pass or fail based on marks
<?php
$marks = 40;

if ($marks >= 50) {
echo "You passed the exam.";
} else {
echo "You failed the exam.";
}
?>

? If...Elseif...Else Statement

? View Code Example
// Display greeting based on time
<?php
$time = 15;

if ($time < 12) {
echo "Good Morning!";
} elseif ($time < 18) {
echo "Good Afternoon!";
} else {
echo "Good Evening!";
}
?>

? Nested If Statement

? View Code Example
// Check both age and citizenship for voting
<?php
$age = 25;
$citizen = true;

if ($age >= 18) {
if ($citizen) {
echo "You can vote in elections.";
} else {
echo "You must be a citizen to vote.";
}
}
?>

? Live Output / Explanation

Based on the input values, PHP evaluates each condition and executes only the matching block. This ensures the program responds differently depending on user data or system state.

? Interactive Concept

Imagine a decision tree where each condition branches the execution path. Nested if statements allow PHP to evaluate multiple layers of logic step by step.

? Use Cases

  • User authentication and authorization checks
  • Form validation logic
  • Displaying content based on time, role, or status
  • Business rules and eligibility checks

✅ Tips & Best Practices

  • Use clear and readable conditions
  • Avoid deeply nested if blocks when possible
  • Use elseif instead of multiple independent if statements

? Try It Yourself

  • Create a script to check if a number is positive, negative, or zero
  • Check student discount eligibility based on age
  • Use nested conditions to validate login and role access