PHP Conditions
Conditions let your program choose what to do, for example show "Pass" or "Fail" depending on marks.
Comparison Operators
A comparison gives true or false.
| Operator | Meaning | Example ($a = 5) | Result |
|---|---|---|---|
== | Equal value | $a == "5" | true |
=== | Equal value and same type | $a === "5" | false |
!= | Not equal | $a != 3 | true |
!== | Not equal or different type | $a !== 5 | false |
> | Greater than | $a > 2 | true |
< | Less than | $a < 2 | false |
>= | Greater or equal | $a >= 5 | true |
<= | Less or equal | $a <= 4 | false |
Prefer === and !==. They check the type too, so they avoid surprises when a form sends the number "5" as text.
Logical Operators
&&(and): true when both sides are true||(or): true when at least one side is true!(not): turns true into false and false into true
if, elseif and else
Example
<?php
$marks = 72;
if ($marks >= 80) {
echo "Grade A";
} elseif ($marks >= 60) {
echo "Grade B";
} elseif ($marks >= 40) {
echo "Grade C";
} else {
echo "Fail";
}Grade B
PHP checks the conditions from top to bottom and runs only the first block whose condition is true.
Combining Conditions
Example
<?php
$age = 20;
$hasCnic = true;
if ($age >= 18 && $hasCnic) {
echo "You can register for the course online.";
} else {
echo "Please visit the institute with a guardian.";
}You can register for the course online.
The Ternary Operator
A short form of if/else for simple choices:
Example
<?php
$stock = 0;
echo $stock > 0 ? "In stock" : "Out of stock";Out of stock
The null coalescing operator ?? gives a default when a value is missing or null:
Example
<?php
$username = null;
echo "Hello, " . ($username ?? "Guest");Hello, Guest
switch
switch compares one value against many cases:
Example
<?php
$day = "Fri";
switch ($day) {
case "Sat":
case "Sun":
echo "Weekend classes at 10 am";
break;
case "Fri":
echo "Short day: classes end at 12";
break;
default:
echo "Regular classes at 4 pm";
}Short day: classes end at 12
Do not forget break. Without it PHP continues into the next case.
match (PHP 8)
match is a cleaner, safer version of switch. It returns a value, uses strict comparison (===), and needs no break.
Example
<?php
$code = 404;
$message = match ($code) {
200 => "OK",
301, 302 => "Moved",
404 => "Page not found",
500 => "Server error",
default => "Unknown status",
};
echo $message;Page not found
Exercise
Exercise
What is the result of 10 === "10" in PHP?
