Page 1 of 1
Array Indexes?
Posted: Mon Nov 08, 2010 11:16 am
by spacebiscuit
Hi guys - is there a function to find the total number of indexes in a nth doimnsion of an array? the count() function seems to work for the first dimension but I can't find anything to find teh second?
Thanks,
Rob.
Re: Array Indexes?
Posted: Mon Nov 08, 2010 11:26 am
by Jonah Bron
None that I know of, but it should be easy to make one.
Re: Array Indexes?
Posted: Mon Nov 08, 2010 11:31 am
by Weirdan
PHP does not have multidimensional arrays (neither has C). It uses arrays of arrays instead - and as such the contained arrays ("rows" in case of 2d array) could be of varying dimensions:
Code: Select all
$a = array( // sizeof == 2
array(1,2,3), // sizeof == 3
array(1,2,3,4,5,6,7), //sizeof == 7
);
Re: Array Indexes?
Posted: Mon Nov 08, 2010 11:39 am
by Jonah Bron
I think he's looking to count all indices of sub arrays, like this:
Code: Select all
function countDimension($array, $n){}
$array = new array( // sizeof == 4
array( // sizeof == 3
1,
2,
array( // sizeof == 2
5,
8
)
),
94,
435,
array( // sizeof == 2
8,
2
)
);
echo countDimension($array, 0); // 4 (4)
echo countDimension($array, 1); // 5 (2+3)
echo countDimension($array, 2); // 2 (2)
echo countDimension($array, 3); // 0 (no such level)
Re: Array Indexes?
Posted: Mon Nov 08, 2010 12:11 pm
by spacebiscuit
Yes I am looking for the sub indicies of the sub array. I need the total as a variable in my for loop, unless there is a while loop I could use in this case?
Rob.
Re: Array Indexes?
Posted: Mon Nov 08, 2010 12:13 pm
by Jonah Bron
A for loop? Maybe you had better post your code so we can see what you're trying to accomplish. You don't always know what you want

Re: Array Indexes?
Posted: Mon Nov 08, 2010 2:22 pm
by AbraCadaver
Probably foreach() as it will loop over each element and you can test for an array and foreach() that or just get the count:
Code: Select all
$a = array( // sizeof == 2
array(1,2,3), // sizeof == 3
array(1,2,3,4,5,6,7), //sizeof == 7
);
foreach($a as $child) {
if(is_array($child)) {
echo count($child);
}
}
If you have multiple nesting then a recursive function would do it.