Question

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..

Was it helpful?

Solution 2

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);

OTHER TIPS

Seems like a job for array_reduce

$toPluck = 'price';
$arr = array(
    array('price' => 2),
    array('price' => 20),
    array('price' => 50),
);

echo array_reduce($arr, function($sum, $item) use($toPluck) {
    return $sum + $item[$toPluck];
}, 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top