3

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?

3 Answers 3

2

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...

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, the comments to this blog post are very informative. The comment #29 would be a nice answer to my question. The author shows, that different functions would be necessary and comment #39 goes into the sort problem.
PHP 7.1 now introduces is_iterable, a function that returns true for an array or an object that implements Traversable.
1

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

1 Comment

For using getArrayCopy I would have to know that it is an object of type ArrayObject. That would not help much if you do not have the time to rewrite a lot of old code.
1

NO

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.