I want to multiply two PHP arrays element-wise.

E.g.

a = [1,2,3]

b = [2,3,4]

output = [2,6,12]

Is there any PHP function to do this?

E.g.

a = [1,2,3]

b = [2,3,4]

output = [2,6,12]

Is there any PHP function to do this?

0 votes

I do not think there is a PHP function to multiply two arrays element-wise. However, you can use *the array_map()* function to call a user-defined function where you can do element-wise multiplication.

Here is an example to show how to use the *array_map()* function for element-wise multiplication:

<?php

function compute_mult($v1, $v2){

return $v1*$v2;

}

$arr1 = array(1,2,3,4,5);

$arr2 = array(2,3,4,5,6);

print_r(array_map("compute_mult", $arr1, $arr2));

?>

The output of the above code is:

Array

(

[0] => 2

[1] => 6

[2] => 12

[3] => 20

[4] => 30

)