Asked  7 Months ago    Answers:  5   Viewed   28 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

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
(
    [0] => 11
    [1] => 22
    [2] => 16
    [3] => 18
    [4] => 3
)
Wednesday, March 31, 2021
 
MKM
answered 7 Months ago
MKM
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
 
Markol
answered 7 Months ago
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] ] = 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, March 31, 2021
 
Viralk
answered 7 Months ago
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
 
coderaider
answered 2 Months ago
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
 
Denis
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :