Thursday, November 20, 2025
HomeLanguagesHow to check a variable is an array or not in PHP...

How to check a variable is an array or not in PHP ?

There are two ways for checking whether the variable is an array or not. We can check whether a variable is an array or not by using the PHP is_array() function and by casting the variable to the array.

Approach 1: We can check whether a variable is an array or not using the is_array() function. The PHP is_array() function is a variable handling function that checks whether a variable is an array or not.

Syntax:

is_array( $variable_name );    

Parameter:  It accepts a single parameter. This parameter must be the variable name for which the check is done if it is an array or not.

Return value: It returns true if the boolean value is TRUE else false.

Example 1: The is_array() function returns true(1) when passed parameter is array else it will return false (nothing).

PHP




<?php
  
$isArr = "friends";
  
if(is_array($isArr)) {
    echo "Array";
} else {
    echo "Not an Array";
}
  
echo "<br>";
  
$isArr = array("smith", "john", "josh");
  
if(is_array($isArr)) {
    echo "Array";
} else {
    echo "Not an Array";
}
  
?>


Output

Not an Array<br>Array

Approach 2: By casting the variable to an array. We have to cast the variable to an array that we want to check.            

For Array:  type casted array === original array

  • Original array:
john, johnson, steve
  • Type casted array:
john, johnson, steve

 For normal variable: type casted array != original array

  •   Original variable:
friends
  •  Type casted variable:
friends, , 

Example 2: After typecasting, an index-based array will be formed.

PHP




<?php
  
$isArr = array("john", "johnson", "steve");
  
if((array)$isArr === $isArr) {
    echo "It is an Array\n";
}
else {
    echo "It is not an Array\n";
}
  
$isArr = "friends";
  
if((array)$isArr === $isArr) {
    echo "It is an Array";
}
else {
    echo "It is not an Array";
}
  
?>


Output

It is an Array
It is not an Array
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6776 POSTS0 COMMENTS
Nicole Veronica
11924 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6904 POSTS0 COMMENTS
Ted Musemwa
7160 POSTS0 COMMENTS
Thapelo Manthata
6859 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS