0

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);
}

3 Answers 3

2

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, PHP has so many helpful methods already implemented and so few are widely known (just like this one to me)
0

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

Comments

0

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
 )

1 Comment

@Rob177, mention not, glad if its works for you. best of luck

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.