How to check an array is multidimensional or not in PHP ?

Given an array (single-dimensional or multi-dimensional) and the task is to check whether the given array is multi-dimensional or not.

Below are the methods to check if an array is multidimensional or not in PHP:

Table of Content

  • Using rsort() function
  • Using Nested foreach Loop

Using rsort() function

This function sorts all the sub-arrays towards the beginning of the parent array and re-indexes the array. This ensures that if there are one or more sub-arrays inside the parent array, the first element of the parent array (at index 0) will always be an array. Checking for the element at index 0, we can tell whether the array is multidimensional or not.

Syntax:

rsort( $array )

Parameters: The rsort() function accepts one parameter.

  • $array: This is the object you want to pass to the function.

Example 1: PHP program to check if an array is multidimensional or not using the rsort function.

php
<?php
$myarray = array( 
    
    // Default key for each will 
    // start from 0 
    array("Beginner", "For", "Beginner"), 
    array("Hello", "World") 
); 

// Function to check array is
// multi-dimensional or not
function is_multi_array( $arr ) {
    rsort( $arr );
    return isset( $arr[0] ) && is_array( $arr[0] );
}

// Display result
var_dump( is_multi_array( $myarray ) );
?>

Output
bool(true)

Example 2: Another PHP program to check an array is multidimensional or not using count function.

php
<?php
// Declare an array
$Beginner = array(1 => 'a', 2 => 'b', 3 => array("Learn", "Contribute", "Explore"));
$gfg = array(1 => 'a', 2 => 'b');

// Function to check array is
// multi-dimensional or not
function is_multi($Beginner) {
    
    $rv = array_filter($Beginner, 'is_array');
    
    if(count($rv)>0) return true;
    
    return false;
}

// Display result
var_dump(is_multi($Beginner));
var_dump(is_multi($gfg));
?>

Output
bool(true)
bool(false)

Note: Try to avoid use count and count_recursive to check that the array is multi-dimension or not cause you may don’t know to weather the array containing a sub-array or not which is empty.

Using Nested foreach Loop

To check if an array is multidimensional in PHP using nested foreach loop, iterate through each element and if any element is an array, return true; otherwise, return false. This method traverses all levels of nested arrays.

Example: This example shows the use of the above-explained approach.

PHP
<?php

function is_multidimensional(array $array) {
    foreach ($array as $value) {
        if (is_array($value)) {
            return true;
        }
    }
    return false;
}

$array1 = [1, 2, 3];
$array2 = [[1, 2], [3, 4]];

echo "Array 1 is multidimensional: " . (is_multidimensional($array1) ? "Yes" : "No") . "\n";
echo "Array 2 is multidimensional: " . (is_multidimensional($array2) ? "Yes" : "No") . "\n";

?>

Output
Array 1 is multidimensional: No
Array 2 is multidimensional: Yes


Contact Us