Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 765
marcosh Avatar asked Dec 18 '22 15:12

marcosh


1 Answers

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
}
like image 75
ShiraNai7 Avatar answered Jan 03 '23 14:01

ShiraNai7