Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sanjayacloud's avatar

How to get sum from inside the foreach

Hi everyone,

I am passing cost array like

 <input name="cost[]" />

in my method I do like below to save it to database

$itemsArray = array();
        $i = 1;
        foreach($request['cost'] as $cost){
            $itemsArray[$i] = $cost;
            $i++;
        }

$data = new model;
$data->cost =  json_encode($itemsArray);

I wan to get sum of all these cost array. Anyone have idea about how to do this calculation ?

0 likes
7 replies
mstrauss's avatar

Depends on what the $cost var looks like inside the foreach loop. Assuming it is something like '5' (number in a string), it'll probably go something like this:

    $totalCost = 0; 
        foreach($request['cost'] as $cost){
            $totalCost += $cost;
        }

Then the total cost would be available in the $totalCost variable. You may also want to check each $cost variable before adding it to the sum to make sure it is a number like:

        foreach($request['cost'] as $cost){
            if (is_numeric($cost)) {
                 $totalCost += $cost;
            }
       }
Cronix's avatar

@snapey Why convert the php array ($request->cost) to a collection first instead of just using the native array_sum()?

jlrdw's avatar

You do realize a small one liner query will do a sum.

You really need to study and practice aggregate functions.

Please or to participate in this conversation.