# Best method for sum two arrays [closed]

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"?

29

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
(
 => 11
 => 22
 => 16
 => 18
 => 3
)
``````
Wednesday, March 31, 2021

18

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);
``````
Wednesday, March 31, 2021

38

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

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

?>
``````

Output of `\$data_summ`:

``````Array
(
 => 1.74
 => 17.37
)
``````

If I understand you correctly.

Wednesday, March 31, 2021

91

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.

Thursday, August 12, 2021

16

Behind the scenes, the two do effectively the same thing, except that in option 1 you're passing in `T`'s class object and in option 2 you're passing in `T[]`'s class object.

I prefer option 1 because it's shorter and easier to read. Then again, it's the same as `Array.newInstance` with a cast added, so I'm not sure that your method adds a lot of value. :-)

Wednesday, August 25, 2021