Search code examples
phparraystraversable

How to detect if object is Traversable in PHP?


How can I detect the variable is a Traversable object to use in foreach loops?

if(is_traversable($variable)) {
    return (array) $variable;
}

Solution

  • Use instanceof to determine if the object is Traversable

    if($variable instanceof \Traversable) {
      // is Traversable
    }