Introduction

The is_iterable() function is a built-in function in PHP 7.1 and above that checks whether a variable is iterable or not. An iterable is a data type that can be looped over using a foreach loop.

Syntax

The syntax of the is_iterable() function is as follows:

bool is_iterable(mixed $var)

The function takes a single parameter, $var, which is the variable to be checked for being iterable. The function returns true if the variable is iterable, and false otherwise.

Example Usage

Here is an example of how to use the is_iterable() function in PHP:

<?php
$var1 = [1, 2, 3];
$var2 = "hello";
echo is_iterable($var1) . "\n"; // output: 1 (true)
echo is_iterable($var2) . "\n"; // output: (false)
?>

In this example, we define two variables: $var1 is an array of integers, and $var2 is a string. We then use the is_iterable() function to check whether each variable is iterable. The output shows that $var1 is iterable (true), while $var2 is not iterable (false).

Conclusion

The is_iterable() function is a useful tool for checking whether a variable is iterable in PHP. It can be used to ensure that a variable can be looped over using a foreach loop before attempting to do so, or to handle iterable and non-iterable variables in a particular way. By using this function, developers can ensure that their code is working with the correct data types and avoid errors that may occur when working with mixed data types.

Practice Your Knowledge

What is the functionality of the 'is_iterable' function in PHP?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?