I would like to delete all elements from an array that don\'t meet some condition.
For example, I have this 2D array:
[
[\'UK\', \'12\', \'Sus\',
Use array_filter. It allows you to perform a check on each item by providing a callback. In that callback function, return true for items that match your criteria. array_filter
returns an array with a all the items that don't match your criteria removed.
For instance, your example array could be filtered like this:
$array = [
['UK', '12', 'Sus', 'N'],
['UK', '12', 'Act', 'Y'],
['SQ', '14', 'Act', 'Y'],
['CD', '12', 'Act', 'Y']
];
$filtered_array = array_filter($array, function ($item) {
return count($item) >= 4 &&
($item[0] == 'UK' || $item[0] == 'CD') &&
$item[1] == '12' &&
$item[3] == 'Y';
});
print_r($filtered_array);