Can someone help me how to code the differences of the temperature . For example, in channel one the difference should be 3 . channel two should be 10, channel three should be 2. Also, if I change the temperature to negative. how should I code it ? HELP
<?php
$a1=array(
"channelOne"=>"45",
"channelTwo"=>"100",
"channelThree"=>"20"
);
foreach($a1 as $Name=>$Temperature) {
echo "Channel_Name"."<br>".$Name."<br>"."Actual_Temperature"."<br>".$Temperature."<br>";
}
$a2=array(
"channelOne"=>"48",
"channelTwo"=>"90",
"channelThree"=>"22"
);
foreach($a2 as $Name=>$Temperature_Now) {
echo "Channel_Name"."<br>".$Name."<br>"."Temperature_Now"."<br>".$Temperature_Now."<br>";
}
?>
you can use the array_map function for this
$a1=array(
"channelOne"=>"45",
"channelTwo"=>"100",
"channelThree"=>"20"
);
$a2=array(
"channelOne"=>"48",
"channelTwo"=>"90",
"channelThree"=>"22"
);
$diff = array_map(
function ($a1, $a2)
{
return abs($a1-$a2);
}, $a1,$a2
);
print_r($diff);
Fiddle:http://phpfiddle.org/main/code/cig-k2n
and you want to keep the keys intact you can use array_walk like this.
$a1=array(
"channelOne"=>"45",
"channelTwo"=>"100",
"channelThree"=>"20"
);
$a2=array(
"channelOne"=>"48",
"channelTwo"=>"90",
"channelThree"=>"22"
);
array_walk($a1,
function (&$v, $k) use ($a1,$a2)
{
$v = abs($a1[$k]-$a2[$k]);
});
print_r($a1);
Fiddle: http://phpfiddle.org/main/code/njd-qeh
Reference: