A question about multidimensional array?

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
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

A question about multidimensional array?

Post by mudkicker »

I've an array like this =>

$i is the number of users and $be is what he is. (It is either "member" or "guest")

$arr[$i][$be]
(for example : $arr[3]["member"] gives mi the info that 3rd person is a member.)

What i want to ask is...
How can i find the number of "member"s in this multidimensional array?
:roll:
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

count($array) - the fn doesn't care whether the array elements are values or arrays ie returns same count regardless if you have a multi-dimensional array containing 6 sub-arrays, or a one dimensional array containing 6 values..

Actually, you could use a one dimensional array here if you can set the numerical keys explicitly to the user numbers:

array(1=>'member', 32=>'guest', 554=>'member', etc)

set the array values like this:

array[$i]

..where $i is the user number.
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post by mudkicker »

ok that's known, but...

For example there are 25 elements in this array and 12 are "member". How can i find that they are 12 elements?

not only this count() fn does work!
qartis
Forum Contributor
Posts: 271
Joined: Sat Dec 14, 2002 4:43 pm
Location: BC, Canada
Contact:

Post by qartis »

Code: Select all

$i=0;
foreach ($array as $user_type){
if ($user_type == "member"){
$i++;
}
}
echo "There are $i members.";
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Code: Select all

<?php

$i = 0;
foreach($arr as $subarray) {

    foreach($subarray as $value) {

        IF ($value == 'member') {

            $i++;
        }
    }
}

echo $i;

?>
Last edited by McGruff on Thu Aug 11, 2005 2:12 am, edited 1 time in total.
ik
Forum Commoner
Posts: 34
Joined: Thu Jul 10, 2003 5:33 am
Location: Lancs Uni, UK
Contact:

Post by ik »

But you don't need multidimentional array for this task :D

Code: Select all

$people=array(
   "John"=>"member",
   "Steve"=>"guest"
);


$count=0;
foreach($people as $key=>$val) &#123;
   if ($val=="member") count++;
&#125;
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Yes.
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post by mudkicker »

Thank you people! :D
Post Reply