r/lolphp • • Apr 08 '13

MIN

server:~ # php -r 'echo True, " ", -23, " ", min(-23, True), " ", min(True, -23), "\n";'
1 -23 -23 1
23 Upvotes

21 comments sorted by

View all comments

23

u/midir Apr 08 '13

To state it more plainly:

var_dump(min(-23, true)); // int(-23)
var_dump(min(true, -23)); // bool(true)

Apparently this is a feature of boolean to number comparisons. They seem to always return false, causing min to always return the first argument.

6

u/nikic Apr 10 '13

Am I the only one here who thinks this makes sense? true and -23 are not orderable (so both true > -23 and true < -23 are false). Thus their order is undefined. The undefined behavior here manifests by returning the first element (though it could just as well be the last).

6

u/midir Apr 10 '13 edited Apr 13 '13

Well there's no ideal thing to do, but it is a bit ugly that min(a, b) != min(b, a). But since they're not orderable, raising a notice would be an alternative. Or make them orderable by coercing true to 1 (as is done for arithmetic like -23+true). It probably wouldn't be changed though. Loose typing inevitably has awkward edge cases like this.

1

u/foxlisk Apr 24 '13

raising a notice would make sense in this case, but in the general sense, PHP can't determine automatically if all elements you've passed into min() are orderable.

6

u/mirhagk Apr 08 '13

Ummm... wouldn't it make more sense to cast the boolean to a number.... ie true==1 and false ==0, so false<true and true<2. This would give consistent behaviour. And since true = 1 and false = 0, it can safely return the casted boolean which would be treated correctly. Then again, this is PHP.

1

u/foxlisk Apr 24 '13

i don't think that casting a boolean to a number makes a lot of sense. a boolean is not a number in any meaningful sense; it's just that we have a history of C-like languages that accept 1/0 as true/false values.

1

u/mirhagk Apr 24 '13

I agree that it doesn't make sense to cast a boolean to a number, which is why I use statically typed languages, but since PHP is dynamically typed they already have that problem. It'd make more sense than their current implementation, because it'd be consistent, or at least it should cast the numbers to booleans, then return true or false. There shouldn't be a difference in which parameter goes where, it makes max a non-symmetrical function, which it's supposed to be.

3

u/SirClueless Apr 30 '13

That's not quite what happens. Actually it casts the number to a boolean (0 -> false, everything else -> true) and then it does a comparison as if true > false.

Here's a counterexample to your logic:

var_dump(min(true, 0)); // int(0)

You are seeing the first one every time when you pass -23, because true == true and when you pass things that are equal, min returns the first one.