How can I detect the variable is a Traversable
object to use in foreach
loops?
if(is_traversable($variable)) {
return (array) $variable;
}
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; })())
);
Use instanceof
to determine if the object is Traversable
if($variable instanceof \Traversable) {
// is Traversable
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With