Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 592
Milad Rahimi Avatar asked Jul 29 '15 13:07

Milad Rahimi


2 Answers

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; })())
);
like image 192
masakielastic Avatar answered Oct 21 '22 13:10

masakielastic


Use instanceof to determine if the object is Traversable

if($variable instanceof \Traversable) {
  // is Traversable
}
like image 14
John Conde Avatar answered Oct 21 '22 13:10

John Conde