25

Is there a way to determine how many dimensions there are in a PHP array?

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
Brian
  • 26,662
  • 52
  • 135
  • 170
  • Possible duplicate of [Is there a way to find out how "deep" a PHP array is?](http://stackoverflow.com/questions/262891/is-there-a-way-to-find-out-how-deep-a-php-array-is) – jeremy Mar 22 '16 at 06:26

8 Answers8

23

Nice problem, here is a solution I stole from the PHP Manual:

function countdim($array)
{
    if (is_array(reset($array)))
    {
        $return = countdim(reset($array)) + 1;
    }

    else
    {
        $return = 1;
    }

    return $return;
}
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • 14
    This is not entirely correct. Because it only tests the first element of the arrays. So this only gives the expected outcome when you're sure it's a evenly distributes array of arrays. You'll have to loop through all elements to truly know variable depths. (Or perhaps some spiffy traversal algorithm I'm not aware of) – Decent Dabbler Jan 23 '10 at 06:21
5

you can try this:

$a["one"]["two"]["three"]="1";

function count_dimension($Array, $count = 0) {
   if(is_array($Array)) {
      return count_dimension(current($Array), ++$count);
   } else {
      return $count;
   }
}

print count_dimension($a);
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
2

Like most procedural and object-oriented languages, PHP does NOT natively implement multi-dimensional arrays - it uses nested arrays.

The recursive function suggested by others are messy, but the nearest thing to an answer.

C.

symcbean
  • 47,736
  • 6
  • 59
  • 94
1

This one works for arrays where each dimension doesn't have the same type of elements. It may need to traverse all elements.

$a[0] = 1;
$a[1][0] = 1;
$a[2][1][0] = 1;

function array_max_depth($array, $depth = 0) {
    $max_sub_depth = 0;
    foreach (array_filter($array, 'is_array') as $subarray) {
        $max_sub_depth = max(
            $max_sub_depth,
            array_max_depth($subarray, $depth + 1)
        );
    }
    return $max_sub_depth + $depth;
}
goat
  • 31,486
  • 7
  • 73
  • 96
1

Here's a solution that worked for me to get the number of dimensions of an arrays that is not evenly distributed.

function count_dimension($array, $count = 0) {
$maxcount = 0;
foreach ($array as $key) {
    if(is_array($key)) {
        $count = count_dimension(current($key), ++$count);
        if($count > $maxcount) {
            $maxcount = $count;
        }
    } else {
        if($count > $maxcount) {
            $maxcount = $count;
        }
    }
}

return $maxcount;}
Imgrund
  • 21
  • 4
1

You could use the following single-line statement to differentiate between 1-D and 2-D arrays

if (gettype(reset($array)) == "array")

This returns true for a 2-D array and a false for a 1-D array.

Waseem
  • 11
  • 1
0

was corrected at Some issues with jumping from one function to another in a loop in php


This double function will go to the last dimension of each array in $a and when its not an array anymore it will echo the number of loops it did to get there with a delimiter |. The downside of this code is it only echoes and cannot be returned (in normal way).

function cc($b, $n)
{
    $n++.' ';
    countdim($b, $n);

}
function countdim($a, $n = 0)
{
    if(is_array($a))
    {
        foreach($a as $b)
        {
            cc($b, $n);
        }
    }else
    {
        echo $n.'|';
    }
}
countdim($a);

Here i made a function with return, but.. its a return from html then "GET" back to php on button click.. I dont know any other way to make it work.. so just name your array to $a and hit the button :/

$max_depth_var = isset($_REQUEST['max_depth_var']) ? $_REQUEST['max_depth_var'] : 0;
?>
<form id="form01" method="GET">
<input type="hidden" name="max_depth_var" value="<?php
function cc($b, $n)
{
    $n++.' ';
    bb($b, $n);
}
function bb($a, $n = 0)
{
    if(is_array($a))
    { 
        foreach($a as $b)cc($b, $n); 
    }else
    {
    echo $n.', ';
    };
}
bb($a); ?>">
<input type="submit" form="form01" value="Get max depth value">
</form><?php
$max_depth_var = max(explode(', ', rtrim($max_depth_var, ",")));
echo "Array's maximum dimention is $max_depth_var.";
Leo Tahk
  • 420
  • 1
  • 6
  • 15
0

If only the innermost array has items, you can use the following function:

function array_dim($array = []) {
    $dim = 0;
    $json = json_encode($array);
    $json_last_index = strlen($json) - 1;

    while (in_array($json[$json_last_index - $dim], ['}', ']'])) {
        $dim++;
    }

    return $dim;
}

If you want to calculate the maximum array dimension you can use the following function:

function max_array_dim($array = []) {
    $json = json_encode($array);

    $step = 0;
    $max = 0;
    for ($i = 0; $i < strlen($json); $i++) {
        if (in_array($json[$i], ['[', '{'])) {
            $step++;
        }
        if (in_array($json[$i], [']', '}'])) {
            $step--;
        }
        $max = max($max, $step);
    }

    return $max;
}
gadolf
  • 1,035
  • 11
  • 19