What are some common ways to group and total values in PHP arrays based on specific keys?

To group and total values in PHP arrays based on specific keys, you can use a combination of array functions like array_reduce, array_key_exists, and isset. First, iterate through the array and check if the key exists in a new result array. If it does, add the value to the existing total. If not, create a new key in the result array with the value.

$data = [
    ['key' => 'A', 'value' => 10],
    ['key' => 'B', 'value' => 20],
    ['key' => 'A', 'value' => 15],
    ['key' => 'C', 'value' => 5],
];

$result = array_reduce($data, function($carry, $item) {
    if (array_key_exists($item['key'], $carry)) {
        $carry[$item['key']] += $item['value'];
    } else {
        $carry[$item['key']] = $item['value'];
    }
    return $carry;
}, []);

print_r($result);