Search code examples
phparrayaccess

How to check for arrayness in PHP?


The best I could come up is

function is_array_alike($array) {
  return is_array($array) || (is_object($array) && $array instanceof ArrayAccess && $array instanceof Traversable && $array instanceof Serializable && $array instanceof Countable);
}

Ugh. Is there something more pretty?

Edit: the test for is_object seems unnecessary. I have added a section to the instanceof PHP manual about that.


Solution

  • Well, since you did use the word "pretty" in your post, just a quick suggestion on cosmetic changes for readability:

    function is_array_or_alike($var) {
      return is_array($var) ||
               ($var instanceof ArrayAccess  &&
                $var instanceof Traversable  &&
                $var instanceof Serializable &&
                $var instanceof Countable);
    }
    

    Explanation of changes:

    1. Function name change: "is_array_alike" -> "is_array_or_alike" just to make it clear that both array-ness and alike-ness are being tested.

    2. Param/arg name change: $array -> $var because "$array" is already sort of presupposing that the argument is of type array.

    3. Stacking &&'ed conditions for readability and conformance to Drupal coding-standard: 80-char line max. Since you are one of the Drupal core maintainers I guess I am assuming this function might possibly go into Drupal, so probably you would have done this before committing anyway.

    4. You are correct that the is_object() is unnecessary. In Java it would be necessary because instanceof would throw a compile-time error if the first operand weren't an object, but I checked just now in PHP and there is no error, just a result of bool(false).

    I second paulmatthews86's suggestion that you provide a use case. It's hard to provide recommendations if we don't know the criteria. For example, to borrow a bit from the duck-typing paradigm point of view, the instanceof tests would be useful but not necessarily mandatory or even complete. If you are more interested in what the $var can do and how it behaves in certain contexts then you could use reflection to check for the existence of the methods that need to be invoked on it later, or you could test that it behaves as expected when passed to array functions. e.g. Does it "work" with array_udiff_assoc, array_chunk, etc. If these behaviors are more important for your use cases then these tests might supersede the instanceof type-testing, although of course there would be a lot of overlap.

    Hope this helps. Interested to see what you finally decide upon if you decide to post it.