Reputation: 7632
I have some legacy code and refactored an array to an ArrayObject. Now I have problems checking, if a variable is an array:
if (is_array($entity) && $otherCondition) {
// do something
}
The function is_array()
returns false
on an ArrayObject. See this report.
Simplest solution would be to use something like this:
function is_traversable($var) {
return is_array($var) || $var instanceof Traversable;
}
Is there some native way for PHP to do a check like this?
Upvotes: 3
Views: 1252
Reputation: 16741
is the answer to your question. An array is an array and an object is an object.
So, if you change an array to an object you should change all the checks. I don't like your is_traversable($var)
function because it means you only do half a job of refactoring you code. You should replace is_array($entity)
by $entity instanceof myEntityClass
or is_object($entity)
.
In any case you should not see arrays
as old fashioned. It can very well be that an array should become an object, but there's nothing wrong with arrays as such.
Upvotes: 1
Reputation: 3236
according to http://blog.stuartherbert.com/php/2010/07/19/should-is_array-accept-arrayobject/, you have to make the custom method you wrote in order to do what you wish...
Upvotes: 2
Reputation: 809
ArrayObject does contain a method named getArrayCopy() which allow you to get an array copy of your ArrayObject. I suppose that most of array built-in functions can be applied on this copy ;)
Doc : http://php.net/manual/fr/arrayobject.getarraycopy.php
Upvotes: 1