How to check if variable is array?... or something array-like
If you are using foreach
inside a function and you are expecting an array or a Traversable object you can type hint that function with:
function myFunction(array $a)
function myFunction(Traversable)
If you are not using foreach
inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:
if (is_array($a) or ($a instanceof Traversable))
foreach
can handle arrays and objects. You can check this with:
$can_foreach = is_array($var) || is_object($var);
if ($can_foreach) {
foreach ($var as ...
}
You don't need to specifically check for Traversable
as others have hinted it in their answers, because all objects - like all arrays - are traversable in PHP.
More technically:
foreach
works with all kinds of traversables, i.e. with arrays, with plain objects (where the accessible properties are traversed) andTraversable
objects (or rather objects that define the internalget_iterator
handler).
(source)
Simply said in common PHP programming, whenever a variable is
- an array
- an object
and is not
- NULL
- a resource
- a scalar
you can use foreach
on it.