11

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

if(is_traversable($variable)) {
    return (array) $variable;
}
Milad Rahimi
  • 3,464
  • 3
  • 27
  • 39

2 Answers2

16

is_iterable can be used since PHP 7.1.

// https://wiki.php.net/rfc/iterable
var_dump(
    true === is_iterable([1, 2, 3]),
    true === is_iterable(new ArrayIterator([1, 2, 3])),
    true === is_iterable((function () { yield 1; })())
);
masakielastic
  • 4,540
  • 1
  • 39
  • 42
  • I assume that the traversable checking is to make sure the conditions listed at https://stackoverflow.com/a/6251125/859837 are met. Not too sure but it is_iterable might give you a false positive because arrays are iterable but not traversable. – Francisco Luz Jul 15 '18 at 04:42
14

Use instanceof to determine if the object is Traversable

if($variable instanceof \Traversable) {
  // is Traversable
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 6
    A teeny note to add that if this code is not in the global namespace it will evaluate to `false` unless Traversable is imported or fully-qualified, so the OP should add `use Traversable;` or use `\Traversable` to their code. – Darragh Enright Jul 29 '15 at 13:31
  • 4
    It should be noted as mentioned in the comments on the Traversable phpdoc page, that objects and arrays can be iterated through with something like foreach but are NOT instances of Traversable. – Scott Mar 02 '16 at 20:58