Is there a way to determine how many dimensions there are in a PHP array?
Is there a way to determine how many dimensions there are in a PHP array?
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;
}
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);
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.
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;
}
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;}
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.
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;
}