Search code examples
phpbooleancomparison

php int comparison "smaller or equal than" returns empty or null?


The following expression

echo ('dfsdfds: '.(int)$item[0] . '   ' . 
(int)$box[0] . '   ' . 
( ( (int)$item[0] <= (int)$box[0] )?true:false) );

echoes this

dfsdfds: 70 25 

The values come form a StdClass Object so the values are stored as a string, therefore the cast to int. I would expect the comparison expression <= to return either 1 or 0 but not null or empty... What is wrong? what am I not thinking thorugh? I have tried to replace true with TRUE and false with FALSE, I have tried to output the expression itself but the output didn't change... it's always empty


Solution

  • This is due to some strange (although documented) default behaviour in PHP when converting between data types:

    Boolean FALSE is converted to "" (the empty string).

    You can change your code to e.g. this to see a difference:

    echo ('dfsdfds: '.(int)$item[0] . '   ' . 
    (int)$box[0] . '   ' . 
    ( ( (int)$item[0] <= (int)$box[0] )?'true':'false') );
    

    Or if you want to have 0 or 1 respectively, you can force a cast to int:

    echo ('dfsdfds: '.(int)$item[0] . '   ' . 
    (int)$box[0] . '   ' . 
    ( ( (int)$item[0] <= (int)$box[0] )?true:(int)false) );
    

    (true is already automatically converted to "1")