3v4l.org

run code in 300+ PHP versions simultaneously
<?php $stocks = [ ['product_id'=>2, 'stocks'=>50], ['product_id'=>3, 'stocks'=>100], ['product_id'=>4, 'stocks'=>20], ['product_id'=>5, 'stocks'=>60] ]; $sales = [ ['product_id'=>4, 'quantity'=>3], ['product_id'=>5, 'quantity'=>30] ]; foreach ($stocks as &$row) { // modify by reference foreach ($sales as $k => $row2) { // search for product_id match if ($row['product_id'] == $row2['product_id']) { $row['stocks'] -= $row2['quantity']; // subtract unset($sales[$k]); // eliminate match from lookup array break; // assuming $sales['product_id'] values are unique } } } var_export($stocks);

preferences:
30.86 ms | 404 KiB | 5 Q