3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = [ ['id' => 1, 'value' => 'a'], ['id' => 2, 'value' => 'b'], ['id' => 3, 'value' => 'c'], ['id' => 4, 'value' => 'a'], ['id' => 5, 'value' => 'e'], ['id' => 6, 'value' => 'j'], ]; // Extract all the ids $ids = array_column($array, 'id'); // Filter the array to find elements where 'value' is 'a' $filtered = array_filter($array, function ($el) { return $el['value'] === 'a'; }); // Initialize toDelete and toUpdate $toDelete = $ids; $toUpdate = null; // Default value for toUpdate // If 'a' is found, set toUpdate to null if (!empty($filtered)) { // Find the last index with value 'a' $lastAIndex = max(array_keys($filtered)); // Remove the last 'a' id from the toDelete array $toDelete = array_diff($toDelete, [$array[$lastAIndex]['id']]); // Set toUpdate to null because 'a' is found $toUpdate = null; } else { // If no 'a' found, set toUpdate to the id of the last item $toUpdate = end($array)['id']; // Last id in the array // Remove that last id from toDelete $toDelete = array_diff($toDelete, [$toUpdate]); } // Prepare the result array $result = [ 'toDelete' => array_values($toDelete), // Reindex the array after diff 'toUpdate' => $toUpdate, ]; // Print the result print_r($result);
Output for 8.2.0 - 8.2.27, 8.3.0 - 8.3.16, 8.4.1 - 8.4.3
Array ( [toDelete] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 [4] => 6 ) [toUpdate] => )

preferences:
41.05 ms | 406 KiB | 5 Q