Viewed   64 times

I have two arrays:

$a = array(10, 2, 5, 10, 0);
$b = array(1, 20, 11, 8, 3);

I need to sum up and get the result:

$c = array(11, 22, 16, 18, 3);

Any suggestions on how do this without "foreach"?

 Answers

5

a simple approach could be

$c = array_map(function () {
    return array_sum(func_get_args());
}, $a, $b);

print_r($c);

Or if you could use PHP5.6, you could also use variadic functions like this

$c = array_map(function (...$arrays) {
    return array_sum($arrays);
}, $a, $b);

print_r($c);

Output

Array
(
    [0] => 11
    [1] => 22
    [2] => 16
    [3] => 18
    [4] => 3
)
Thursday, September 1, 2022
3

Convert the string into an array and use array_sum.

array_sum(explode(' ', $re));

Edit

Sorry, misunderstood:

$letters = array('a','b','c', 'd', 'e');

$replace = array( 1,  5,  10, 15 , 20);

$text = "abd cde dee ae d" ;

$new_array = explode(' ', $text);

$sum_array = array();

foreach ($new_array as $string)
{

  $nums = str_split($string);

  foreach ($nums as &$num)
  {
    $num = str_replace($letters, $replace, $num);
  }

  $sum_array[] = array_sum($nums);

}

echo implode(' ', $sum_array);
Tuesday, August 2, 2022
 
2

Try something like this:

<?php

$data = Array ( 
    Array ( 0 => '18', 1 => '1,07' ),
    Array ( 0 => '8', 1 => '0,44' ),
    Array ( 0 => '8', 1 => '0,67' ),
    Array ( 0 => '18', 1 => '0,55' ), 
    Array ( 0 => '18', 1 => '0,19' ),
    Array ( 0 => '8', 1 => '0,48' ),
    Array ( 0 => '18', 1 => '2,59' ),
    Array ( 0 => '8', 1 => '0,15' ),
    Array ( 0 => '18', 1 => '12,97' ) 
);

// predefine array
$data_summ = array();
foreach ( $data as $value ) {
    $data_summ[ $value[0] ] = 0;
}

foreach ( $data as $list ) {
    $number = str_replace( ",", ".", $list[1] ) * 1;
    $data_summ[ $list[0] ] += (float)$number;
}

?>

Output of $data_summ:

Array
(
    [8] => 1.74
    [18] => 17.37
)

If I understand you correctly.

Wednesday, December 7, 2022
1

I know this is an old question but I was just discussing this with someone and we came up with another solution. You still need a loop but you can accomplish this with the Array.prototype.map().

var array1 = [1,2,3,4];
var array2 = [5,6,7,8];

var sum = array1.map(function (num, idx) {
  return num + array2[idx];
}); // [6,8,10,12]
Sunday, September 25, 2022
2

There's certainly nothing to enable this in the language. I don't know of anything in the standard libraries either, but it's trivial to put the code you've written into a utility method which you can call from anywhere you need it.

Wednesday, October 19, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :