php sum values in associative array code example

Example 1: sum of associative array in php

<?php
$items = [
    ['label' => 'cake', 'name' => 'Cake', 'price' => 150],
    ['label' => 'pizza', 'name' => 'Pizza', 'price' => 250],
    ['label' => 'puff', 'name' => 'Veg Puff', 'price' => 20],
    ['label' => 'samosa', 'name' => 'Samosa', 'price' => 14]
];

$arrSum = array_sum(array_column($items, 'price', 'name'));
print "Sum of Array : ".$arrSum."<br/>";
?>

Example 2: php sum array elements

<?php
$a=array(5,15,25);
echo array_sum($a);
?>

Tags:

Php Example