简体   繁体   中英

subtracting array values from another unequal array

I have the following which works just fine when the arrays are of an equal length:

(example)

$highNums = array(10,20,30,40,50,60);
$lowNums = array(0,1,2,3,4,5);

$result = array();
for($i=0;$i<count($highNums);$i++)
{
    $result[$i] = $highNums[$i]-$lowNums[$i];
}

The problem lies in that the array keys are dates (months) pulled from the database and where there is, say, 'january' and a value in the $lowNums array there won't always be a 'january' record in the $highNums.

Is there any way to detect any missing values in each array and fill them with 0? }

foreach ($highNums as $key=>$val) {

     if(array_key_exists($key, $lowNums)){
           $result[$key] = $highNums[$key]-$lowNums[$key];
     }else{
           $result[$key]=0;
     }

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM