Even though ArrayObject
implements Serializable
, the assumption is wrong that an object must implement it to be array-like.
The opposite is the case. You can make use of Serializable
to effectively prevent the serialization of an object. So I would consider to remove it from the interface check.
Also if you use instanceof
without an object, you will see a (fatal) error. I suggest you delegate the check of an object that is "array-like" to a leaf function and make your function that is less strict with the input types make use of it:
function is_array_or_object_arraylike($var) {
return is_array($var)
|| (is_object($var) && is_object_arraylike($var))
;
}
function is_object_arraylike($obj) {
return $obj instanceof ArrayAccess
&& $obj instanceof Traversable
&& $obj instanceof Countable
;
}
Also keep in mind, even an object is array-like, it does not work with most array functions. nor would it work well with foreach
, so you should better outline about which array features you're looking for here.
Is there something more pretty?
doubt it. – Nugent$array['test']
) or that you can iterate over it like an array? – Erlindaerline