PHP is_array() function

The is_array() function is an inbuild function in PHP. This function is used to check whether a variable is an array or not . Suppose we want a foreach loop and before implementing foreach loop we have to check whether the variable on which we are implementing foreach is array or not because foreach works on array variable.

Syntax:

is_array(mixed $value): bool

Parameters :

Value – Single parameter(variable) required to be evaluated.

Return Type :

Bool – true or false .

Return Value:

Return true if value is an array , False otherwise.

Examples :

<?php
$fruits = array('Mango', 'Banana', 'Apple');

 var_dump(is_array($fruits));  "<\n>";// out put True

 echo is_array($fruits);  "<\n>"; // output 1 
 
 // As $fruits is an array it execute if statement
 if(is_array($fruits))
 echo "\n Variable fruits is an array.\n";
 else
 echo "Variable Fruits is not an array.";
 
 
 
 echo "----------------------------------------------------\n";
 
 
 
$str = " Welcome to bptutorials";

 var_dump(is_array($str));  "<\n>";// out put False

 echo is_array($str);  "<\n>"; // output  
 
 // As $str is not an array it execute else statement
 if(is_array($str))
 echo "\n Variable str is an array.";
 else
 echo "Variable str is not an array.";

Output :

is_array() function PHP

Explaination :

In above example $fruits is an array. To check it we write var_dump(is_array($fruits)); . Here var_dump() output True as bool value. You can also confirm it as echo is_array($fruits); and it returns 1 ( True). As if(is_array($fruits)) is true so statement echo “\n Variable fruits is an array.\n”; is executed.

Now come to the second one $str . It is string variable and when we var_dump() it as var_dump(is_array($str)); it return boon value False. We can also check it as echo is_array($str); and it output blank. So statement if(is_array($str)) is false. So else statement will executed ie. echo “Variable str is not an array.”;

Share This!

Leave a Reply

Your email address will not be published.