Checking for Arrays and Iterator Implementations
When writing a loop over a variable in PHP, the default instinct is often to use a foreach statement. However, this construct only works if the variable represents an iterable structure. If the input is NULL, a scalar integer, or a custom class that hasn't been designed for iteration, the code will either throw a fatal error or silently fail depending on PHP's version and context. A common pattern to guard against this is checking with is_array():
if (is_array($var)) {
foreach ($var as $item) {
// process $item
}
}
This approach handles standard arrays perfectly, but it leaves a gap: objects. Specifically, PHP allows you to iterate over any object that implements the Iterator interface (or its siblings like IteratorAggregate). If your code needs to handle data from external APIs or custom models that return these specific types, relying solely on is_array() will cause a crash when an object is passed instead.
To detect whether a class implements a specific interface like Iterator, you cannot use the is_a() function directly against the interface name in the same way you would check for inheritance from a base class. While is_a($object, 'SomeClass') checks if $object is an instance of SomeClass, there isn't a direct equivalent "is_interface" operator for checking implementation in older PHP versions without extra logic.
The standard solution for this specific check is the instanceof operator combined with the interface name:
if ($var instanceof Iterator) {
foreach ($var as $item) {
// process $item
}
}
If you need to support both arrays and iterator objects within a single block, you can combine the checks. It is important to note that instanceof returns false for primitives like integers or strings, and it also returns false if the variable is NULL. Therefore, placing an explicit null check or relying on the fact that instanceof handles non-objects gracefully (returning false) is a common pattern.
However, there is a more robust approach available in modern PHP: using the is_iterable() function. Introduced in PHP 7.1, this superglobal function acts as a unified gatekeeper for iteration logic. It returns true if the variable is an array or implements the Iterator interface (or IteratorAggregate). This eliminates the need to manually write multiple conditional branches checking for specific interfaces.
if (is_iterable($var)) {
foreach ($var as $item) {
// process $item
}
} else {
// Handle non-iterable case, e.g., null or scalar
}
Using is_iterable() is generally preferred because it abstracts the underlying implementation details. You don't need to know if a specific class implements ArrayIterator directly or uses getIterator() via IteratorAggregate; PHP handles that detection internally. This reduces cognitive load and minimizes the risk of missing an edge case where a custom object iterates differently than expected.
One potential pitfall with this strategy is handling NULL. In many contexts, you might want to treat NULL as an empty iterable (resulting in zero iterations) rather than failing the check. Since is_iterable(NULL) returns false, you must explicitly decide how to handle that case. If your application logic requires treating null data as empty, you would need to adjust the condition:
if ($var !== null && is_iterable($var)) {
foreach ($var as $item) {
// process $item
}
}
By consolidating these checks into is_iterable(), you ensure your code remains compatible with standard arrays, objects implementing Iterator, and objects using the getIterator() method, providing a single, reliable entry point for loop logic. For projects built on Laravel, this utility function is often leveraged in data processing pipelines to normalize different input types before mapping or transforming them.
