PHP: filter

I would like to remove all elements from the array that do not meet a specific 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 lines that do not 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?

+3
source share
1 answer

Use array_filter. It allows you to validate each item by providing a callback. In this callback function, return true for items matching your criteria. array_filterreturns an array with all elements that do not match your criteria.

For example, your array of examples can be filtered as follows:

$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);
+7
source

Source: https://habr.com/ru/post/1790243/


All Articles