Ivan T.
Ivan T.

Reputation: 535

How is this (erroneous) comparison done by PHP?

Assume the following code, which tries to determine whether the array has more than 3 elements. Note, that I am aware that this is done normally using count($array) and comparing the integers, but I got curious as to why

$array = [1, 2, 3];
var_dump($array > 3);

returns true, which it, actually, does independently of the value of the right comparison operand in the var_dump, so $array > 3 is no different than $array > 3000.

My question lies in what sort of typecasting happens internally in PHP when an array is compared to an integer in this entirely inappropriate manner, or whether there is a case where this manner is indeed appropriate.

Upvotes: 2

Views: 49

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

From the PHP manual, it says:

array anything array is always greater

array comparison

So when you compare anything with array, then array is greater. I am now going to check array vs. object.

Upvotes: 3

Related Questions