-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArithmeticArray.php
57 lines (53 loc) · 1.7 KB
/
ArithmeticArray.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
/**
* Mathematical operation with arrays
*
* @author Tiago A C Pereira
*/
class ArithmeticArray
{
/**
* Mathematical operation [+,-,*,/].
* Maintains key association.
* Example: $dividend = ['A'=>10,'B'=>20]; $divisor = ['A'=>2,'B'=>10]; ($dividend/$divisor) result ['A'=>5, 'B'=>2].
* @param array $data
* @param array $data2
* @param string $symbol
*
* @return array
*/
public function operation($data, $data2, $symbol)
{
$result = [];
foreach($data as $item){
foreach($data2 as $value){
if(key($data) == key($data2)){
if(!isset($result[key($data)]))
$result[key($data)] = $item;
switch($symbol){
case '+':
$result[key($data)] = round($result[key($data)]+$value,2);
break;
case '-':
$result[key($data)] = round($result[key($data)]-$value,2);
break;
case '*':
$result[key($data)] = round($result[key($data)]*$value,2);
break;
case '/':
$result[key($data)] = round($result[key($data)]/$value,2);
break;
default:
$result = [];
break;
}
}
next($data2);
}
reset($data2);
next($data);
}
arsort($result);
return $result;
}
}