Is there a way to determine how many dimensions there are in a PHP array?
+2
A:
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
2010-01-23 05:16:39
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)
fireeyedboy
2010-01-23 06:21:17
A:
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
2010-01-23 05:22:46
A:
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
2010-01-23 10:56:46
A:
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;
}
chris
2010-01-23 20:21:42