Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic Operations in Arrays with PHP

Tags:

arrays

php

I have two arrays

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

and also another array carries

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

I need to divide these two arrays(ie,$data1/$data2) and store value to $data3[]. I need to get it as follows

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

If someone knows of an easy way to do this would be of great help. Thanks

like image 918
Aadi Avatar asked May 31 '10 07:05

Aadi


1 Answers

You can do that 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 as of PHP 5.3 you can even use a lambda function to compress that to one row:

$data3 = array_map(function($a, $b) { return $a / $b; }, $data1, $data2);
like image 146
Tatu Ulmanen Avatar answered Sep 22 '22 04:09

Tatu Ulmanen