Search code examples
phparraysis-emptyarrayobject

Php - empty ArrayObject


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?


Solution

  • 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
    }