3v4l.org

run code in 500+ PHP versions simultaneously
<?php $first = [ 1 => 4.00, 2 => 3.00, 3 => 8.00, 4 => 4.88, 5 => 7.88, 10 => 17.88 ]; $second = [ 1 => 2.00, 3 => 4.00, 4 => 2.88, 7 => 5.0, 8 => 6.00 ]; // Merge the 2 original arrays and preserve the keys // https://stackoverflow.com/q/17462354/296555 // The duplicate items' value will be clobbered at this point but we don't care. We'll set them in the `array_walk` function. $output = $first + $second; // Create an array of the duplicates. We'll use these keys to calculate the difference. $both = array_intersect_key($first, $second); // Foreach element in the duplicates, calculate the difference. // Notice that we're passing in `&$output` by reference so that we are modifying the underlying object and not just a copy of it. array_walk($both, function($value, $key) use (&$output, $first, $second) { $output[$key] = $first[$key] - $second[$key]; }); // Finally, sort the final array by its keys. ksort($output); var_dump($output); // Output //array (size=8) // 1 => float 2 // 2 => float 3 // 3 => float 4 // 4 => float 2 // 5 => float 7.88 // 7 => float 5 // 8 => float 6 // 10 => float 17.88

preferences:
56.12 ms | 1660 KiB | 5 Q