Php

Conditional Statements

✅ Conditional Statements in PHP

Conditional statements allow your program to make decisions based on conditions — like “if a user is logged in, show their profile; otherwise, show the login form.”


1. if Statement

Executes a block of code only if the condition is true.

php
$age = 20;

if ($age >= 18) {
echo "You are an adult.";
}


2. if...else Statement

Executes one block of code if the condition is true, another if it’s false.

php
$age = 16;

if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}


3. if...elseif...else Chain

Checks multiple conditions in sequence.

php
$score = 75;

if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}


4. Ternary Operator (Shorthand if...else)

Useful for simple conditions in a single line.

php
$is_logged_in = true;

echo $is_logged_in ? "Welcome back!" : "Please log in.";


5. switch Statement

Good for checking one variable against multiple values.

php
$day = "Monday";

switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is coming!";
break;
default:
echo "Have a nice day!";
}


Best Practices

  • Always use braces {} for clarity, even for one-line blocks.

  • Use === instead of == for strict comparison (type + value).

  • Sanitize user input before using it in conditions (e.g., htmlspecialchars()).


Summary Table

Type Use Case
if Run code if a condition is true
if...else Run one of two code blocks
if...elseif...else Handle multiple options
?: (ternary) Shorthand for simple if...else
switch Compare one value against many cases

Leave a Reply

Your email address will not be published. Required fields are marked *