Count quiz score per category

I’m stuck trying to figure how to count scores in an array per category. It’s a 20 question multiple choice quiz. 4 categories each containing 5 questions. All 20 questions are presented randomly.


if (isset($_POST['submit'])) {
		
		//$total = array();
		
		foreach ($_POST["category"] as $key => $value) {
		        echo "Question " . $key . "<br>";
		        echo "Category " . $value . "<br>";
		        echo (is_null($_POST["answer"][$key]) ? "Unanswered" : "Answer <b>" . $_POST["answer"][$key]) . "</b><br><br>";
				
				
				//$total = $_POST["answer"][$key]+=$value;
				
				//$score = ARRAY_SUM($total);
		
		}
		
		
		//print_r($total);
		
		
		
	
	   } //end if submit

A simple COUNT won’t even count just all scores. uncommented lines are things I tried to at least get counting working. Basically
I just want to count scores per category. E.g.:

Count $_POST[“answer”][$key] while $value is the same.

Echo category 1 score is 7
category 2 score is 5
category 3 score is 8
category 4 score is 6

Anyone an idea how I can do this?

Is this what you’re looking for?

<?php
	$total = array();
	foreach($_POST["category"] as $key => $value):
		echo "Question " . $key . "<br>";
		echo "Category " . $value . "<br>";
		echo (is_null($_POST["answer"][$key]) ? "Unanswered" : "Answer <b>" . $_POST["answer"][$key]) . "</b><br><br>";
		
		if(!array_key_exists($value,$total)): $total[$value] = ""; endif;
		$total[$value] += $_POST["answer"][$key];
			
	endforeach;
	
	//Show Array for testing
	//echo "<pre>";
	//print_r($total);
	//echo "</pre>";
	
	//Display
	foreach($total as $cat => $score):
		echo "<b>Category:</b> " . $cat . " <b>Total Score:</b> " . $score . "<br>";
	endforeach;
	
?>

That did it. Thanks!