Monday, 13 August 2018

How to Test/Check if a Variable is an Array in PHP?

Problem:

You have a variable. You want to check if it is a simple variable or an array. 

Solution:

You can test whether a variable is an array or not in few ways. Here you’ll see two methods-

Method 1: Using is_array() function

The is_array() function takes your variable and returns TRUE if the variable is an array, otherwise it returns FALSE. See the example below-
1
2
3
4
5
6
7
8
9
<?php
    $days = array("Sunday", "Wednesday", "Friday");
    echo is_array($days) ? "it is an array" : "it is not an array";
     
    echo "<br />";
 
    $salary = "$9000";
    echo is_array($salary) ? "it is an array" : "it is not an array";    
?>
Output:it is an array
it is not an array

Method 2: Using gettype() function

The gettype() function takes your variable and returns “array” if the variable is an array. See the example below-
1
2
3
4
5
6
7
8
9
<?php
    $days = array("Sunday", "Wednesday", "Friday");
    echo (gettype($days) == "array") ? "it is an array" : "it is not an array";
     
    echo "<br />";
 
    $salary = "$9000";
    echo (gettype($salary) == "array") ? "it is an array" : "it is not an array";    
?>
Output:it is an array
it is not an array

0 comments:

Post a Comment