Am trying to write a simple PHP function that uses both && and || function in php but am only able to use the && function, i get a desired result as shown with the below code
<?php
$srt = "asc";
if($srt != "" && $srt != "asc"){
echo "close";
} else {
echo "open";
}
?>
output >> open
But when i add the || function to it i get the wrong result
<?php
$srt = "asc";
if($srt != "" && $srt != "asc" || $srt != "desc"){
echo "close";
} else {
echo "open";
}
?>
output >> close
I have also try using AND in place of && and OR in place of || since php accepts both but i still get the same result am new to php so i dont know if what am trying is allowed or not so any advise will be greatly appreciated.
CodePudding user response:
Use extra parenthesis to make it an expression.
if ($srt != "" && ($srt != "asc" || $srt != "desc"))
So you compare $srt != ""
AND $srt != "asc" || $srt != "desc"
.
Your code can be improved for readability as
if (!in_array($srt, ['', 'asc', 'desc']))