Alan Storm Alan Storm - 3 months ago 7
PHP Question

Is there a way to test a variable for "isForEachable"

Using PHP, is there a function/method/way to check if a variable contains something that would be safe to put into a foreach construct? Something like

//the simple case, would probably never use it this bluntly
function foo($things)
{
if(isForEachable($things))
{
foreach($things as $thing)
{
$thing->doSomething();
}
}
else
{
throw new Exception("Can't foreach over variable");
}
}


If your answer is "setup a handler to catch the PHP error", your efforts are appreciated, but I'm looking for something else.

Answer

Well, sort of. You can do:

if (is_array($var) || ($var instanceof Traversable)) {
    //...
}

However, this doesn't guarantee the foreach loop will be successful. It may throw an exception or fail silently. The reason is that some iterable objects, at some point, may not have any information to yield (for instance, they were already iterated and it only makes sense to iterate them once).

See Traversable. Arrays are not objects and hence cannot implement such interface (they predate it), but they can be traversed in a foreach loop.