0

When I am trying to determine if an empty array is greater than 0, but returns true. why php empty array greater than 0 ?

$a = [];
if (is_array($a) && count($a) > 0) {
    die('array');
} elseif ($a > 0) {
    die('ok');
}

it's output 'ok', Can anyone tell me why this is?

ikool
  • 153
  • 1
  • 9
  • 4
    Did you try to open a manual http://php.net/manual/en/language.operators.comparison.php ? – u_mulder Jan 22 '19 at 07:31
  • 1
    Do not expect PHP was implemented in a logic way. There are many comparision results you would not expect. The linked page above says: "array <|>|== anything: array is always greater" – Pinke Helga Jan 22 '19 at 07:48
  • If you know it's an array and you're just checking whether there's anything in it or not, `if ($a)` will work just fine. – Don't Panic Jan 22 '19 at 08:04

3 Answers3

2

http://php.net/manual/en/language.operators.comparison.php According to php documentation, when comparing array against any other type other than array the array is always considered greater. It is just how the comparison is defined. My guess is that when comparing two variables which could be of any type, the comparison rule enforces array to be unequal to any other type.

user3647971
  • 1,069
  • 1
  • 6
  • 13
1

Consider using empty() to check for an empty array, I am of the impression that it does not need to perform the work needed to discover the count to only determine if the array is empty and should be a faster result.

To demonstrate in your scenario ( including the array check, though you should trust it as an array as you're strictly defining it as one but I can understand you are just providing an example and it might be from an unknown source )

$a = [];
if (is_array($a)) {
  die(empty($a) ? 'empty' : 'not empty');
} else {
  die('Not an array');
}
Brendon Moss
  • 134
  • 5
1

enter image description here

Thanks @Quasimodo's clone @u_mulder

ikool
  • 153
  • 1
  • 9