Open In App

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

Last Updated : 22 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Next Article

Similar Reads