I am getting values of two company stocks through a third party website using an API. These are output as two arrays eg
$companyA = array([0] => 100 [1] => 100.20 [2] => 103.20);
$companyB = array([0] => 99 [1] => 101.30 [2] => 105.50);
Each key [0],[1],[2], etc.. represents a day and is the same day for both stock dates. I would like to try and find the difference in values in the array by doing a subtraction for each value. ie 100 - 99, 100.20-101.30, 103.20 - 105.50, etc...
I tried array_diff but it's not working.
Thank you.
You can use array_map
$result = array_map(function ($firstElement, $secondElement) {
return $firstElement - $secondElement;
}, $companyA, $companyB);
You can also try this with basics:
<?
$companyA = array(100,100.20,103.20);
$companyB = array(99,101.30,105.50);
$newArr = array();
foreach ($companyA as $key => $value) {
$newArr[] = ($value-$companyB[$key]);
}
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[0] => 1
[1] => -1.1
[2] => -2.3
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.