How to check for multidimensional nature of an array in PHP

In PHP, you can check if an array is multidimensional by examining whether its first element is itself an array. This approach uses sorting to ensure consistent element ordering, then checks the nature of the first element.

Using rsort() with isset() and is_array()

The following method sorts the array and checks if the first element is an array −

<?php
$my_array = array(
    array("This", "is", "a", "sample"),
    array("Hi", "there")
);

function multi_dim($my_arr)
{
    rsort($my_arr);
    return isset($my_arr[0]) && is_array($my_arr[0]);
}

echo "Is the array multi-dimensional? ";
var_dump(multi_dim($my_array));
?>
Is the array multi-dimensional? bool(true)

Alternative Method

A simpler approach without sorting −

<?php
function is_multidimensional($array)
{
    foreach ($array as $element) {
        if (is_array($element)) {
            return true;
        }
    }
    return false;
}

$single_array = array("apple", "banana", "cherry");
$multi_array = array(
    array("red", "green"),
    array("sweet", "sour")
);

echo "Single array: ";
var_dump(is_multidimensional($single_array));
echo "Multi array: ";
var_dump(is_multidimensional($multi_array));
?>
Single array: bool(false)
Multi array: bool(true)

How It Works

The rsort() method sorts the array in descending order, ensuring consistent element positioning. The isset() function checks if the first element exists, while is_array() determines if that element is itself an array. If both conditions are true, the array is multidimensional.

Conclusion

Both methods effectively detect multidimensional arrays. The rsort() approach ensures consistent ordering, while the foreach method is more straightforward and doesn't modify the original array structure.

Updated on: 2026-03-15T09:02:34+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements