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
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
array(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:
110.27 ms | 1658 KiB | 4 Q