How to Sum Values of an Array With the Same Key in PHP?

A few ways to quickly sum values of an associative array in PHP

PHP has a great number of array-related functions that we can use in different scenarios. Today we look at using these functions and the foreach loop to sum values of an array of the same key in PHP. For the purpose of this article, we'll be using the following PHP associative array:

$items = [
	'item_1' => ['id' => 1, 'name' => 'White Shirt', 'qty' => 2],
	'item_2' => ['id' => 2, 'name' => 'Blue Shirt', 'qty' => 3],
];

We'll be summing the values of the key qty, which should give us the result 5.

Using the foreach Loop

$sum = 0;

foreach ($items as $item) {
	$sum += $item['qty'];
}

echo $sum; // output 5

Although it takes up a few lines of code, this would be the fastest way as it's using the language construct foreach rather than a function call (which is more expensive).

Using array_column()

// PHP 5.5+
echo array_sum(array_column($items, 'qty')); // output 5

Using array_map()

// PHP 4+
function mapArray($item) {
	return $item['qty'];
}

echo array_sum(array_map('mapArray', $items));

// PHP 5.3+
echo array_sum(array_map(
	function($item) {
		return $item['qty'];
	}, $items)
);

// output 5

Using array_reduce()

// PHP 4+
function sumValues($carry, $item) {
	$carry += $item['qty'];
    return $carry;
}

echo array_reduce($items, 'sumValues');


// PHP 5.3+
echo array_reduce($items, function($carry, $item) {
    $carry += $item['qty'];
    return $carry;
});

// output 5

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.