1

I am trying to display the result of the comparison operation ($a > $b) which does not display anything for the below code, whereas the operation ($a < $b) displays the result 1.

I am wondering why the first operation does not return 0 as it is false?

<?php
    $a = 1;
    $b = 5;
    print ($a > $b);
    echo "Output";
    print ($a < $b);
?>
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Ajit
  • 261
  • 3
  • 15

3 Answers3

3

Unfortunately that's an extremely common misconception. 0 "is" not false. false is false, a boolean. 0 is 0, a number. 0 loosely equals false in a non-type safe comparison.

When you echo or print false, it is being cast to a string. false cast to a string is "", an empty string. true cast to a string is "1", the string "1".

Read http://php.net/manual/en/language.types.string.php#language.types.string.casting.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • PHP has no objective standard for truth - it plays hard and fast with the truth. Truth is relative, according to PHP. "True and false are whatever I desire." – Patashu Apr 12 '13 at 01:13
  • @Patashu That's bullcr*p. PHP has perfectly defined [truth tables](http://www.php.net/manual/en/types.comparisons.php), you just have to learn them. PHP is not random. It boils down to the following things being *falsey*: `false`, `0`, `'0'`, `''`, `null`, `array()`. Everything else is *truthy*. – deceze Apr 12 '13 at 01:14
  • @Patashu That comment also has nothing to do with the topic at hand: *type juggling*. – deceze Apr 12 '13 at 01:22
  • You can memorize all of the weird comparison rules in PHP, but it's so easy to get wrong. For example http://phpsadness.com/sad/47 has some of my favourite gotchas, because 'string that contains a number' can suddenly become true when you don't expect it - `"1e1"` being a number for example... – Patashu Apr 12 '13 at 01:31
  • @Patashu But again, that's [perfectly defined behavior](http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.types). And again, you need to learn your language, especially if it has a lot of such automagic going on. It's not like you can't do anything about it and are at the mercy of PHP; you just have to know what your operators do and what the rules are. Every language has its type comparison gotchas, complaining about it doesn't make you a good programmer. – deceze Apr 12 '13 at 01:37
0

Integer comparison ($a < $b) has return type boolean, which can be true or false.
print works in such way that it prints "1" for true and nothing for false.

Martinsos
  • 1,663
  • 15
  • 31
0

It is due to the way in which PHP handles false values.

echo ($a > $b) will also output nothing.

To have your statement output 0 for a false condition you need to cast to an integer:

print (int)($a > $b);
Ken Herbert
  • 5,205
  • 5
  • 28
  • 37