[nycphp-talk] Getting the number of dimensions of an array
Joey Derrico
joeyd473 at gmail.com
Fri May 18 16:27:24 EDT 2012
I am trying to count the number of dimensions in an array. I used my
google-fu and came up with answers that don't actually work because I can
have multi-dimensional array's where one int he middle is multi and the one
after not. Below is my latest set of test code (I have been playing with it
for hours (with varying results), none correct), It currently returns 15
dimensions and should be returning 5
<?php
echo "\n";
$test = new test();
$array = array();
$array[0] = '[0]';
$array[1][0] = '[1][0]';
$array[1][1] = '[1][1]';
$array[2][0][0] = '[2][0][0]';
$array[2][0][1] = '[2][0][1]';
$array[2][1][0] = '[2][1][0]';
$array[2][1][1] = '[2][1][1]';
$array[3][0][0][0] = '[3][0][0][0]';
$array[3][0][0][1] = '[3][0][0][1]';
$array[3][1][0][0] = '[3][1][0][0]';
$array[3][1][0][1] = '[3][1][0][1]';
$array[3][1][1][0] = '[3][1][1][0]';
$array[3][1][1][1] = '[3][1][1][1]';
$array[4][0][0][0][0] = '[4][0][0][0][0]';
$array[4][0][0][0][1] = '[4][0][0][0][1]';
$array[4][1][0][0][0] = '[4][1][0][0][0]';
$array[4][1][0][0][1] = '[4][1][0][0][1]';
$array[4][1][1][0][0] = '[4][1][1][0][0]';
$array[4][1][1][0][1] = '[4][1][1][0][1]';
$array[4][1][1][1][0] = '[4][1][1][1][0]';
$array[4][1][1][1][1] = '[4][0][0][0][1]';
$array[5][0][0][0] = '[5][0][0][0]';
$array[5][0][0][1] = '[5][0][0][1]';
$array[5][1][0][0] = '[5][1][0][0]';
$array[5][1][0][1] = '[5][1][0][1]';
$array[5][1][1][0] = '[5][1][1][0]';
$array[5][1][1][1] = '[5][1][1][1]';
$array[6][0][0] = '[6][0][0]';
$array[6][0][1] = '[6][0][1]';
$array[6][1][0] = '[6][1][0]';
$array[6][1][1] = '[6][1][1]';
$array[7][0] = '[7][0]';
$array[7][1] = '[7][1]';
$array[8] = '[8]';
echo 'The array has '.$test->countNumberOfDimensionsOfAnArray($array)."
dimensions\n";
//echo print_r($array,TRUE);
class test
{
public function isMultDimensionalArray($array)
{
$return = FALSE;
if(is_array($array)){
foreach($array as $value){
if(is_array($value)){
$return = TRUE;
}
}
}
return $return;
}
public function countNumberOfDimensionsOfAnArray($array)
{
$dimensions = 0;
if(is_array($array)){
$dimensions++;
foreach($array as $key=>$value){
if($this->isMultDimensionalArray($value)){
$dimensions = $dimensions +
$this->countNumberOfDimensionsOfAnArray($value);
}
}
}
return $dimensions;
}
}
?>
Joey Derrico
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20120518/f3806caf/attachment.html>
More information about the talk
mailing list