Please house i want to know which of this is better to use, i want to get the total sum of the array, so i did this
$do = array(
array('name' => 'apple', 'price' => 40),
array('name' => 'orange', 'price' => 30),
array('name' => 'pawpaw', 'price' => 15),
);
$total = 0;
foreach($do as $am){
$total += $am['price'];
}
echo $total;
Or is it better to first make another array or $am[‘price’] and then use array_sum() on it, which could be more better to use.
Thank you
You should use array function
$sum = array_reduce($do, function($sum, $item)
{
$sum += $item->price;
return $sum;
});
1 Like
really this entirely a brand new approach, so there is something called array_reduce() more like the array_map() that has a call back function.
Thanks.
$total = array_sum(array_column($do, 'price'));
1 Like
This is the most simplest code for this, really beautiful, am learning alot here. thanks
[off-topic]
Try combining all three arrays into a single array because a single entity is easier to move around if used in other parts of the application.
[/off-topic]
system
Closed
January 18, 2022, 6:08am
7
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.