← Back to Chapters

PHP If Else Statement

? PHP If Else Statement

? Quick Overview

The if...else statement allows you to execute one block of code if a condition is true and another block if the condition is false.

? Key Concepts

  • Decision making in PHP
  • Boolean condition evaluation
  • Alternative execution paths

⚙️ Syntax / Theory

? View Code Syntax
// Basic if else syntax in PHP
<?php
if (condition) {
echo "Condition is true";
} else {
echo "Condition is false";
}
?>

? Code Example

? View Code Example
// Check voting eligibility using if else
<?php
$age = 16;

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

? Live Output / Explanation

If the value of $age is less than 18, the else block executes and displays a message indicating ineligibility.

? Interactive Example

Change the value of $age and predict the output before running the script.

?️ Live Logic Simulator

Enter an age to see which "PHP" block would execute:

You are not eligible to vote.

(This simulates the PHP logic above using JavaScript)

? Use Cases

  • User authentication checks
  • Form validation logic
  • Role-based access control
  • Dynamic content rendering

✅ Tips & Best Practices

  • Always use curly braces for clarity
  • Write readable conditions
  • Keep logic simple and clean

? Try It Yourself

  • Create a file named if_else_statement.php
  • Check whether a number is even or odd using if...else
  • Display output using echo