Skip to main content

PHP Conditions

Conditions allow programs to make decisions.

Without conditions, every program would execute exactly the same way every time.

Conditions are used everywhere:

  • Login Systems
  • Permissions
  • APIs
  • PocketMine Plugins
  • Authentication
  • Web Panels

Boolean Values

A condition always evaluates into:

true
false

if Statement

$age = 18;

if ($age >= 18) {
echo "Adult";
}

Output:

Adult

if else

$online = false;

if ($online) {
echo "Player Online";
} else {
echo "Player Offline";
}

elseif

$rank = "vip";

if ($rank === "owner") {

echo "Owner";

} elseif ($rank === "admin") {

echo "Admin";

} elseif ($rank === "vip") {

echo "VIP";

} else {

echo "Player";

}

Comparison Operators

OperatorMeaning
==Equal
===Identical
!=Not Equal
!==Not Identical
>Greater Than
<Less Than
>=Greater Than Equal
<=Less Than Equal

Examples

Equal

$a = 5;
$b = 5;

if ($a == $b) {
echo "Equal";
}

Identical

$a = 5;
$b = "5";

var_dump($a == $b);
var_dump($a === $b);

Output:

true
false

Greater Than

if ($money > 1000) {
echo "Rich";
}

Less Than

if ($health < 10) {
echo "Low Health";
}

Greater Than Equal

if ($level >= 50) {
echo "Unlocked";
}

Less Than Equal

if ($health <= 0) {
echo "Dead";
}

Logical Operators

OperatorMeaning
&&AND
`
!NOT

AND Operator

if (
$isOnline &&
$isAdmin
) {

echo "Staff Member";

}

OR Operator

if (
$rank === "owner" ||
$rank === "admin"
) {

echo "Staff";

}

NOT Operator

if (
!$player->isBanned()
) {

echo "Allowed";

}

Ternary Operator

$status =
$online
? "Online"
: "Offline";

Null Coalescing Operator

$name =
$_GET["name"] ?? "Guest";

Switch Statement

switch ($rank) {

case "owner":
echo "Owner";
break;

case "admin":
echo "Admin";
break;

case "vip":
echo "VIP";
break;

default:
echo "Player";
}

Match Expression

PHP 8+

$prefix = match ($rank) {

"owner" => "[Owner]",
"admin" => "[Admin]",
"vip" => "[VIP]",

default => "[Player]"
};

PocketMine Example

if (
$sender->hasPermission(
"zyro.admin"
)
) {

$sender->sendMessage(
"Access Granted"
);

}

Login Example

if (
$username === "admin" &&
$password === "123"
) {

echo "Login Success";

}

Common Mistakes

Wrong

if ($rank = "admin")

This assigns a value.


Correct

if ($rank === "admin")

Best Practices

✅ Prefer:

===
!==

instead of:

==
!=

✅ Use Match expressions in PHP 8+


✅ Avoid deeply nested conditions.


Exercises

  1. Check if age is adult.
  2. Create rank permission system.
  3. Build login validator.
  4. Convert switch to match.

Quiz

Which operator checks identical values?
===

Which operator means OR?
||

References

https://www.php.net/manual/en/control-structures.if.php

https://www.php.net/manual/en/control-structures.switch.php

https://www.php.net/manual/en/control-structures.match.php


Next Chapter

➡ PHP Loops