Arithmetic operations in arrays with PHP

I have two arrays

$data1 = array() $data1 = array( '10','22','30') 

and also another array contains

 $data2 = array() $data2 = array( '2','11','3'); 

I need to separate these two arrays (i.e. $ data1 / $ data2) and save the value of $ data3 []. I need to do it as follows

 $data3[] = array('5','2','10') 

If someone knows of a simple way to do this, it will be very helpful. Thanks

+6
arrays php
source share
1 answer

You can do this with a simple foreach statement:

 $data1 = array('10','22','30') $data2 = array('2','11','3'); $data3 = array(); foreach($data1 as $key => $value) { $data3[$key] = $value / $data2[$key]; } 

Alternatively, you can use array_map :

 function divide($a, $b) { return $a / $b; } $data3 = array_map("divide", $data1, $data2); 

And with PHP 5.3, you can even use the lambda function to compress this line into one line:

 $data3 = array_map(function($a, $b) { return $a / $b; }, $data1, $data2); 
+8
source share

All Articles