1

Lets say I have the following code:

<?php
$a = array(0,1,2);
$b = array(0,1,2);
$c = $a + $b;
print_r($c);
?>

it does not work. Obviously, I can add each corresponding element of the vector by having a "foreach" loop, but I am wondering if there is a predefined function to prevent hard-coding.

Massoud
  • 503
  • 4
  • 13
  • Possible duplicate of [Can't concatenate 2 arrays in PHP](https://stackoverflow.com/questions/2650177/cant-concatenate-2-arrays-in-php) – gawi Jun 24 '17 at 09:30

2 Answers2

1

I think you could do this with array_map

http://php.net/manual/en/function.array-map.php

something like

$a1 = array(4,6,7);
$a2 = array(3,6,1);
$a3 = array_map(function($a, $b){ return $a + $b;}, $a1, $a2);

It probably wouldn't be any more efficient than just straight up placing it in-line, but if you just want it to look pretty then this might do it.

edit: heres a similar answer Best method for sum two arrays

slackOverflow
  • 177
  • 1
  • 2
  • 12
0

I needed this in a projekt where i needed this to call many, many times and I was only interested adding values of on vector (1-dimensional array) to another. so slight deviation from the question asked:

/**
 * add vector $b to $a
 * $param &number[] $a call by reference
 * $param number[] $b array to add
 */
function array_add(&$a, $b)
{
    for($i=count($a);--$i>=0;)
        $a[$i] += $b[$i];
}

But the php optimizer might be just as fast.

theking2
  • 2,174
  • 1
  • 27
  • 36