PHP is_iterable() - Check Iterable
The is_iterable() function in PHP is a simple yet powerful tool to check whether a given variable is iterable. Iterability means the variable can be used in a foreach loop, such as an array or an object implementing the Traversable interface. This tutorial covers everything you need to know about is_iterable(), including usage examples, best practices, and common pitfalls.
Prerequisites
- Basic knowledge of PHP syntax and variables
- Familiarity with PHP arrays and objects
- PHP version 7.1.0 or higher (where
is_iterable()was introduced)
Setup Steps
- Ensure your environment is running PHP 7.1 or newer. You can check your PHP version by executing:
php -v - Create a PHP file, e.g.,
is_iterable-example.php, with your code editor. - Run your script through the CLI or via a web server to test
is_iterable()functionality.
Understanding the PHP is_iterable() Function
The is_iterable() function accepts one argument β any PHP variable β and returns true if the variable can be iterated over in a foreach loop, otherwise it returns false.
bool is_iterable(mixed $var)
Explained Examples
Example 1: Checking an Array
<?php
$array = [1, 2, 3];
if (is_iterable($array)) {
echo "Array is iterable.\n";
foreach ($array as $value) {
echo $value . "\n";
}
} else {
echo "Not iterable.";
}
?>
Output:
Array is iterable.
1
2
3
Example 2: Checking an Object Implementing Traversable
<?php
class MyCollection implements IteratorAggregate {
private $items = ['a', 'b', 'c'];
public function getIterator() {
return new ArrayIterator($this->items);
}
}
$obj = new MyCollection();
if (is_iterable($obj)) {
echo "Object is iterable.\n";
foreach ($obj as $item) {
echo $item . "\n";
}
} else {
echo "Not iterable.";
}
?>
Output:
Object is iterable.
a
b
c
Example 3: Non-Iterable Variable
<?php
$intVar = 123;
if (is_iterable($intVar)) {
echo "Iterable";
} else {
echo "Not iterable";
}
?>
Output:
Not iterable
Best Practices When Using is_iterable()
- Use before looping: Always use
is_iterable()before aforeachloop when the variableβs type is uncertain to avoid runtime errors. - Handle non-iterables gracefully: Provide alternate logic or error messages if a variable is not iterable.
- Combine with type declarations: When possible, use scalar and iterable type hinting in functions and class methods for clarity and safety.
- Prefer iterables over arrays for flexibility: Accepting iterable parameters allows your code to work with arrays and objects seamlessly.
Common Mistakes
- Assuming
is_iterable()returnstruefor all objects (it only returns true if the object implementsTraversable). - Failing to check iterability before using
foreach, leading to fatal errors if the variable is not iterable. - Using
is_iterable()on scalar types without proper validation or context, resulting in unnecessary checks. - Not upgrading PHP versionsβ
is_iterable()is only available in PHP 7.1 and above.
Interview Questions
Junior-Level Questions
- Q1: What does the
is_iterable()function check in PHP?
A: It checks whether a variable can be iterated in aforeachloop (arrays or objects implementingTraversable). - Q2: When was
is_iterable()introduced in PHP?
A: It was introduced in PHP 7.1.0. - Q3: What types of variables return
truewhen passed tois_iterable()?
A: Arrays and objects implementing theTraversableinterface. - Q4: Can a string variable be iterable according to
is_iterable()?
A: No, strings do not returntrueforis_iterable(). - Q5: Why should you use
is_iterable()before aforeach?
A: To prevent errors by ensuring the variable can be safely iterated.
Mid-Level Questions
- Q1: Describe how
is_iterable()differs fromis_array().
A:is_iterable()returnstruefor arrays and objects implementingTraversable, whileis_array()returnstrueonly for arrays. - Q2: How would you check if an object is iterable without using
is_iterable()?
A: By checking if the object implements theTraversableinterface using$obj instanceof Traversable. - Q3: Can
is_iterable()help in accepting flexible function parameters? How?
A: Yes, by allowing functions to accept any iterable type (arrays or Traversable objects), enhancing flexibility. - Q4: What happens if you use a
foreachon a non-iterable variable?
A: It results in a fatal error in PHP. - Q5: Can you add type hints to enforce that a function argument is iterable in PHP 7.1+?
A: Yes, by using theiterabletype hint in the function signature.
Senior-Level Questions
- Q1: Explain how the internal mechanics of
is_iterable()determines iterability of a variable.
A: It checks if the variable is an array or an object implementing theTraversableinterface, which supports internal iteration. - Q2: How can
is_iterable()improve stability in complex applications handling multiple data types?
A: It prevents runtime errors by ensuring only truly iterable variables are processed in loops, improving robustness. - Q3: Discuss the difference in performance implications between using
is_iterable()vs. directly usingforeachon uncertain data types.
A:is_iterable()adds a minimal overhead but avoids expensive fatal errors from invalidforeachusage, thus improving overall performance stability. - Q4: Can user-defined classes be made iterable, and how does
is_iterable()interact with them?
A: Yes, by implementingIteratororIteratorAggregate.is_iterable()returns true if the class implementsTraversable. - Q5: Is it possible to polyfill
is_iterable()on PHP versions lower than 7.1? Provide a basic implementation.
A: Yes, using a user-defined function checking ifis_array()is true or the variable is an instance ofTraversable(if available).
Frequently Asked Questions (FAQ)
What variable types are considered iterable in PHP?
Arrays and objects implementing the Traversable interface.
Can I use is_iterable() on scalar types like integers or strings?
No, scalar types always return false because they are not iterable.
Is is_iterable() compatible with all PHP versions?
No, it requires PHP 7.1.0 or newer.
Why should I check iterability even if I expect an array?
Because your variable might unexpectedly be null, a scalar, or an object that is not iterable, which would cause errors during iteration.
How does is_iterable() differ from using is_array()?
is_array() only checks for arrays, while is_iterable() checks both arrays and iterables (objects implementing the Traversable interface).
Conclusion
The PHP is_iterable() function is a valuable addition to your variable handling toolkit, especially useful for writing reliable and flexible iteration code. By verifying whether a variable can be safely looped over, you can prevent runtime errors and build more robust applications. Remember to always check iterability when working with user input or dynamically typed variables, make use of type hints, and follow best practices outlined in this tutorial.