Search code examples
phpmultidimensional-arrayfilteringmultiple-conditionsarray-filter

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?


Solution

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