How can I calculate the value of one string containing few values?
For example,
$toPluck = 'price';
$arr = $gamesWorth;
$plucked = array_map(function($item) use($toPluck) {
echo $item[$toPluck];
}, $arr);
The webpage displays 2, 20, and 50.
I want to calculate them both and echo to the page 72.
I tried to find a solution on the web and on that website, but I can't find it..
There are a few ways to handle it, but a simple modification to your existing code would be to return
values from your array_map()
and sum the resultant array with array_sum()
.
$toPluck = 'price';
$arr = $gamesWorth;
$plucked = array_map(function($item) use($toPluck) {
// Uncomment this if you want to print individual values
// Otherwise the array_map() produces no output to the screen
// echo $item[$toPluck];
// And return the value you need
return $item[$toPluck];
}, $arr);
// $plucked is now an array
echo array_sum($plucked);