How to use OR in PHP if statement
If we want the If statement to execute when at least one of the given conditions is met, we can use OR
, which in the case of conditional statements in PHP is expressed by the symbol ||
.
<?php
if($animal == 'dog' || $vehicle == 'car') {
// do something if animal == dog OR if vehicle == car
}
?>
Example:
Print the content if the user has a Moderator or Admin rank.
<?php
$userRank = 'admin';
if($userRank == 'admin' || $userRank == 'moderator') {
echo 'Secret content';
} else {
echo 'Access denied';
}
?>
Output: Secret content
Example 2:
Make a match if two users made at least one, the exact same choice.
<?php
$userX = [
'favColor' => 'blue',
'favNumber' => 14,
'favSport' => 'football',
];
$userY = [
'favColor' => 'green',
'favNumber' => 2,
'favSport' => 'football',
];
if( ($userX['favColor'] == $userY['favColor']) || ($userX['favNumber'] == $userY['favNumber']) || ($userX['favSport'] == $userY['favSport'])) {
echo "It's a match!";
}
?>
Output: It’s a match!