Rob177
Rob177

Reputation: 27

PHP - Best way to count the number of things in array

I'm running a foreach loop on an array of students, that have a key ['all_user_grades']. What is the best way to count the number of As,Bs,Cs,Ds,Es and fails for each student in the array.

Here's what my array looks like:

[11] => Array
        (
            [id] => 10
            [All_User_Grades] => A, A, D, A, E
        )

Here's what my foreach looks like so far:

foreach($user_grades as $k => $v){
        $aug = $v['All_User_Grades'];
        $all_user_grades_arr = explode(',', $aug);
}

Upvotes: 0

Views: 56

Answers (3)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

You can try this way using array_count_values, i have used for single array, you change as per your requirements. See Demo http://ideone.com/YrGfPD

 //PHP
 $v=array('Id'=>10,'All_User_Grades'=>'A,A,D,A,E');
 $aug = $v['All_User_Grades'];
 $all_user_grades_arr = explode(',', $aug);
 echo '<pre>';
 print_r(array_count_values($all_user_grades_arr));
 echo '</pre>';

 //OUTPUT
 Success time: 0.02 memory: 24448 signal:0
 Array
 (
    [A] => 3
    [D] => 1
    [E] => 1
 )

Upvotes: 0

kero
kero

Reputation: 10638

You can use substr_count() for this like so

$As = substr_count($aug, 'A');
$Bs = substr_count($aug, 'B');
//etc

or, just like you already did, explode and use the array for calculation

$all_user_grades_arr = explode(',', $aug);
$grades = array('A' => 0, 'B' => 0', ...);
foreach ($all_user_grades_arr as $val) {
    $grades[ trim($val) ]++;
}

The trim() here is necessary to get rid of unnecessary whitespaces

Upvotes: 0

Gergo Erdosi
Gergo Erdosi

Reputation: 42048

You can use the array_count_values() function:

$array = array('A', 'A', 'D', 'A', 'E');
$result = array_count_values($array);

print_r($result);

It outputs:

Array
(
    [A] => 3
    [D] => 1
    [E] => 1
)

Upvotes: 2

Related Questions