views:

100

answers:

1

Hello

lets say I have two arrays

   <?PHP
        $arr1 = array("a","b","c");
        $arr2 = array("1","2","3");

        function multiply_arrays($arr1,$arr2){
           //what is the best way to do that in terms of speed and memory
           return $arr3;
        }
   ?>

what is the best way to multiply them?

the result should be an array with following values:

a1 a2 a3 b1 b2 b3 c1 c2 c3

because I don't want to face an error like this:

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 39 bytes)

Thanks

+5  A: 

A simple nested loop?

function multiply_arrays(array $arr1, array $arr2) {
  $ret = array();
  foreach ($arr1 as $v1) {
    foreach ($arr2 as $v2) {
      $ret[] = $v1 . $v2;
    }
  }
  return $ret;
}

I'm assuming based on your example you mean string concatenation. If not, the innermost lines simply varies to the intended result.

cletus
+1 for looking like the solution. this kind of code probably won't hit the memory limit. only if your array is like millions or billions of elements.
thephpdeveloper