Strange IF condition Behavior

Hi folks,

echo "Days Left : " . $days_left_user . "<br>";
echo "Position ID : " . $pid . "<br>";
echo "Country ID : " . $cid . "<br>";

if(($days_left_user==0) and ($pid==0) and ($cid==0)){
   echo "You must select atlest one option above to filter results.";
   exit;
}else{
   //show search results

}

Now, consider following output

Days Left : 0
Position ID : 0
Country ID : JOR

You must select atlest one option above to filter results.

So why it is showing “You must select atlest one option above to filter results” insted of search results?

Because you are comparing a string to an integer, which is evaluated to true.

var_dump(0 == "a"); // 0 == 0 -> true

http://php.net/manual/en/language.operators.comparison.php

You also should use “===”, as much as possible to check the type comparison is also correct. Like

if(($days_left_user === 0) and ($pid === 0) and ($cid === "")){

Only use “==”, when you need type coercion.

Scott

1 Like

Hi s_molinari

Worked Charm!! Thank you very much for the useful information.

if(($days_left_user==0) and ($pid==="0") and ($cid==="0")){
   echo "You must select atlest one option above to filter results.";
   exit;
}
  • days left is usually an integer and other two variables are string variables comes from html list controls.

You can also check it that way:

if(($days_left_user==0) && !$pid && !$cid)){
    echo "You must select atlest one option above to filter results.";
    exit;
}

Condition !$var (“not var”) equals to true when $var contains empty string, empty array or zero (integer or “0”).

2 Likes

Thanks buddy got it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.