How can I add two arrays of numbers to each other like a matrix?

171
December 16, 2019, at 11:50 AM

I have two arrays:

$a = [1 , 2, 3 ,4];
$b = [5 , 6 , 7 , 8];
$c = $a + $b ;

How to find $c? I read about array_push or array_merge, but they don't solve my problem because they just add the arrays to each other straightly like two strings. I need add them to each other like a matrix, index to index!

Answer 1

One approach could be to use array_map() and pass through your two arrays after the callback function like so:

$c = array_map(function($x, $y) {
  return $x + $y;
}, $a, $b);

Output:

Array ( [0] => 6 [1] => 8 [2] => 10 [3] => 12 )

For an approach that should work for N arrays, you can use the splat operator (...):

$arrs = [$a, $b]; // [a1, a2, ..., an];
$c = array_map(function(...$nums) {
    return array_sum($nums);
}, ...$arrs);
Rent Charter Buses Company
READ ALSO
array_merge in PHP not overriding values

array_merge in PHP not overriding values

I'm having some strange issue with array_merge

137
PHP DOMXPath Get Value with Full Path - No ID

PHP DOMXPath Get Value with Full Path - No ID

I am trying to get a value of an element through a direct XPath as the element has no ID

141
How to modelize privilèges in Symfony 4 database?

How to modelize privilèges in Symfony 4 database?

Hello everyone I want to model a privilege system in my database under symfony 4 and I would like to know if my design is good or not?

148
PHP & MYSQL-How to search words and put them like a sentence for translation?

PHP & MYSQL-How to search words and put them like a sentence for translation?

I am creating where a user can search like "How are you" and it outputs the translation to "Como son tu"

123