Filter out all rows that do not match multiple rules across four different elements

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', 'N'],
    ['UK', '12', 'Act', 'Y'],
    ['SQ', '14', 'Act', 'Y'],
    ['CD', '12', 'Act', 'Y']
]

and I would like to delete all rows that don’t match this format:

['UK' or 'CD', '12', Any Value, 'Y']

leaving me with this filtered array:

[
    ['UK', '12', 'Act', 'Y'],
    ['CD', '12', 'Act', 'Y']
]

How can I do this?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply