Mahmoud
Mahmoud

Reputation: 571

Comparing PHP arrays with integers, what is the real behavior

Today I faced a weird behavior on PHP (v: 7.1) arrays.

$emptyArray = [];

echo empty($emptyArray);

echo count($emptyArray);

echo (($emptyArray > 0));

The first two echos results is known (empty : true , count: 0), but the last one which confused me returned true!

Why PHP considered an empty array is larger than zero ?!

Upvotes: 1

Views: 72

Answers (2)

axiac
axiac

Reputation: 72256

Why PHP considered an empty array is larger than zero ?!

It is written in the documentation: when it is compared with an object of a different type, the array is always greater.

Upvotes: 1

deceze
deceze

Reputation: 522382

The answer is to be found in the rules for comparisons between different types:

Operand 1    Operand 2    Result
...          ...          ...
array        anything     array is always greater

Upvotes: 7

Related Questions