Determine number of Dimensions in a PHP Array
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);
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;
}
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; }
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.