Skip to content
Advertisement

Error in if else – understanding concept of if else (or, and priority in iteration statement)

<?php
$st="Success";
if(($st=="SUCCESS" || $st=="Success" || $st=="success") && $st!=0 && $st!="0" && $st!="FAILURE" && $st!="Queued" && $st!="Pending" && $st!="queued" && $st!="pending" && $st!="QUEUED" && $st!="PENDING" )
{
    echo 'success';
}else
if(($st=="FAILURE" || $st=="failure" || $st=="0" || $st==0 || $st=="Failure") && $st!="Queued" && $st!="Pending" && $st!="queued" && $st!="pending" && $st!="QUEUED" && $st!="PENDING" && $st!="SUCCESS" && $st!="Success" && $st!="success" )
{
    echo 'failed';
}else
{
    echo 'nill';
}
?>

Why does my code print nill when I pass Success value in $st ? How does && , || priority work in ifelse statement ?

Advertisement

Answer

As I mentioned, you should be checking for what it is, not what it isn’t, since you’re only checking one variable. If $st is success it can’t be anything else. Same goes for failure/0. You can also eliminate a few checks by converting the variable to lowercase.

if(strtolower($st) == 'success') { // Convert to lowercase and check against "success"
    echo 'Success';
}
else if(strtolower($st) == 'Failure' || (is_integer($st) && $st == 0)) { // convert to lowercase and check if it's "failure" or it's a number and 0
    echo 'Failed';
}
else {
    echo 'nill';
}

If you know you’re passing in success, you can add a var_dump($st); inside of your else check to see what it contains. Make sure to count the characters, as “success ” is not the same as “success”. You can also add a trim($st); before your if checks to remove any extra whitespace from the ends of the value .

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement