The Greatest PHP Value

Just two days ago I asked a PHP-quiz-question in the chatroom on Stackoverflow, something along the lines:

PHP: Which one is greatest?

PHP has a comparison operator to compare if one value is greater than the other (>). Which one of the three values INF, array() and (object) array() is the greatest?

  1. Infinity – INF
  2. Array – array()
  3. Object – (object) array()
  4. undefined

and it really is a PHP Quiz. The undefined means that you can not find out if a single one is the largest. If you want to guess your own, you should not read further yet.

Even the Array is greater than Infinity in PHP, the Array is less than an Object. Now you could say that Object then must be the greatest, however the Object is less than Infinity.

So between these three values you can not formulate any expression in PHP that describes the greatest one therefore the answer is undefined.

$inf    = INF;
$array  = array();
$object = (object) $array;

var_dump($object > $array  and $object > $inf  ); # bool(false)
var_dump($array  > $object and $array  > $inf  ); # bool(false)
var_dump($inf    > $object and $inf    > $array); # bool(false)

So maybe some of them is equal to another? No not as well ;).

So what are the practical implications of this? A simple example that is impacted by that is the sort() function. When a sorting behavior that does not do any type-conversion is used (default), then the result is based on the order in the array and not on the values. That might be unexpected.

As always when I’m puzzled with PHP I write a more or less well formulated question on Stackoverflow about it and ping NikiC. Because he not only answers the question but also makes me learn a lot of new terms and is so firm with PHP internals. See for yourself: PHP Type-Juggling and (strict) Greater/Lesser Than Comparisons which has got quite some traction already.


And if you’re using an older PHP version, the answer might not be undefined. Until PHP 5.1.6 Objects were greater than Infinity like Arrays are but less than Arrays allowing a clear winner: Array is greatest! 🙂

Read On: Comparison operators – PHP Sadness #52 – Very detailed and impressive description and visualization of comparison in PHP.

This entry was posted in Developing, PHP Development, Pressed, The Know Your Language Department and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.