4

The ArrayObject class allows objects to work as arrays. When I check if an ArrayObject is empty, though, the result is always false

echo empty(new ArrayObject()); // returns false

Wouldn't it be more coherent with the behavior of an empty array [] if it returned true?

marcosh
  • 8,780
  • 5
  • 44
  • 74

1 Answers1

12

PHP's ArrayObject isn't interchangeable with arrays. Most array-related functions won't work with it.

The empty() construct only determines whether the given value is falsy (while ignoring undefined variable / index errors). An instance of ArrayObject evaluates to true when it is cast to a boolean.

This would work for both arrays and ArrayObjects (since they implement Countable):

if (!count($variable)) {
    // $variable is an empty array or empty ArrayObject
}
Shira
  • 6,392
  • 2
  • 25
  • 27
  • 1
    (In my opinion it's a shame that PHP doesn't have more generalised and uniform operator overloading (yes, `empty` is essentially an operator), but... oh, well...) – deceze Jun 29 '16 at 15:32