Multidimensional Array Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Texan
Forum Newbie
Posts: 9
Joined: Mon Dec 20, 2004 9:23 pm

Multidimensional Array Question

Post by Texan »

I have an array:

Code: Select all

$var = array('test' => 
             array('sub1', 'sub2', 'sub3'),
             'test1' =>
             array('sub1', 'sub2'),
             'test2');
I know how to get the size of a regular array, but how do I get
the size of the sub array? i.e: how do I get that the sub array
of $var[test] is equal to 3 and that the size of the sub array
$var[test1] is equal to 2?

Thanks
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Just the same way you do with any other array...

Code: Select all

//Enitre array
$entire = count($var);

//Sub array 1
$sub1 = count($var['test']);

//Sub array 2
$sub2 = count($var['test1']);
User avatar
wmasterj
Forum Commoner
Posts: 40
Joined: Mon Aug 18, 2003 5:52 pm
Location: Stockholm, Sweden

Post by wmasterj »

yes...

and then you use a foreach loop. If you want to be able to have even deeper levels of arrays to be tested i suggest you script a function for it.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

No need for any such foreach loop to recursively count.

If you read the documentation count() can do this.

i.e.

Code: Select all

$number = count($array, 1); //Or count($array, COUNT_RECURSIVE);
Post Reply