Quantcast
Viewing all articles
Browse latest Browse all 53

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.

// http://eval.in/15219
$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 Image may be NSFW.
Clik here to view.
;)
.

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.

Image may be NSFW.
Clik here to view.
array-larger-than-infinity

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! Image may be NSFW.
Clik here to view.
:)

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


Tagged: Array, Infinity, Object, Operator, PHP, Quiz Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 53

Trending Articles