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?

3
  • 4
    Did you try to open a manual php.net/manual/en/language.operators.comparison.php ? Commented Jan 22, 2019 at 7: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" Commented Jan 22, 2019 at 7: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. Commented Jan 22, 2019 at 8:04

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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');
}

Comments

1

enter image description here

Thanks @Quasimodo's clone @u_mulder

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.