<?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' => 'a'],
];
// 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);