php array filter use
PHP array_filter Function
Summary: in this tutorial, you’ll learn how to use the PHP array_filter() function to filter elements of an array using a callback function.
Introduction to PHP array_filter() function
When you want to filter elements of an array, you often iterate over the elements and check whether the result array should include each element.
The array_filter() function makes the code less verbose and more expressive:
From PHP 7.4, you can can use the arrow function instead of the anonymous function like this:
The array_filter() function allows you to filter elements of an array using a callback function.
The following ilustrates the syntax of the array_filter() function:
PHP array_filter() function examples
Let’s take some examples to understand the array_filter() function better.
1) Basic array_filter() function example
2) Using callback as a method of a class
Besides a callback, you can pass a method of a class to the array_filter() function like this:
To use the isOdd() method as the callback of the array_filter() function, you use the following form:
If you have a class that has is a static method, you pass the static method as the callback of the array_filter() function:
The following uses the isEven() static method as the callback of the array_fitler() function:
From PHP 5.3, if a class implements the __invoke() magic method, you can use it as a callable. For example:
In this example, the Positive class has the __invoke() magic method that returns true if the argument is positive; otherwise, it returns false.
You can pass an instance of the Positive class to the array_filter() function for including only positive numbers in the result array.
Passing elements to the callback function
By default, the array_filter() function passes the value of each array element to the callback function for filtering.
Sometimes, you want to pass the key, not value, to the callback function. In this case, you can pass ARRAY_FILTER_USE_KEY as the third argument of the array_filter() function. For example:
To pass both the key and value of the element to the callback function, you pass the ARRAY_FILTER_USE_BOTH value as the third argument of the array_filter() function. For example:
In this tutorial, you have learned how to use the PHP array_filter() function to filter elements of an array using a callback.
Поделиться
doctor Brain
мир глазами веб-разработчика
PHP: фильтрация массивов
фильтруем многомерный массив по ключу и значению
время чтения 5 мин.
К счастью, функция array_filter не ограничена только возможностью удалять из массива значения, соответствующие логическому false. В качестве второго параметра array_filter может использовать весьма полезные callback-функции, а это означает, что мы можем делать с массивом, практически все, что захотим.
Давайте рассмотрим возможность фильтрации многомерного массива по ключу и значению.
Исходный массив
Для начала, нам нужны какие-то данные, например, этот небольшой многомерный массив:
Конечно, для лучшего представления данных пригодится функция var_dump:
Фильтрация многомерного массива по ключу
Теперь попробуем отфильтровать массив по ключу (key). Напомню, что в нашем массиве есть два главных ключа: ‘PHPDevelopers’ и ‘C#Developers’. Давайте предположим, что нам требуются только данные для ‘PHPDevelopers’.
По умолчанию функция array_filter возвращает только значения. С помощью третьего параметра мы можем явно указать, что нам требуются только ключи (ARRAY_FILTER_USE_KEY) или и ключи и значения (ARRAY_FILTER_USE_BOTH).
Вот так будет выглядеть наша функция:
Давайте посмотрим, что произойдет, если мы забудем указать третий параметр для array_filter:
Фильтрация многомерного массива по значению
А теперь попробуем отфильтровать в массиве php-разработчиков (PHP Developers) старше сорока лет.
Обратите внимание на следующие моменты:
Получится следующая функция:
Итак, мы отобрали три записи, в каждой из которых возраст разработчика превышает 40 лет:
Вывод
Функция array_filter дает практически неограниченные возможности, например: для простого отбора данных в большом массиве или для фильтрации свойств выбранных в интернет-магазине товаров.
Не забывайте изучить полную документацию для array_filter.
array_filter
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
array_filter — Фильтрует элементы массива с помощью callback-функции
Описание
Список параметров
Возвращаемые значения
Возвращает отфильтрованный массив.
Список изменений
Примеры
Пример #1 Пример использования array_filter()
Результат выполнения данного примера:
Результат выполнения данного примера:
Пример #3 array_filter() с указанным mode
Результат выполнения данного примера:
Примечания
Если callback-функция изменяет массив (например, добавляет или удаляет элементы), поведение этой функции неопределённо.
Смотрите также
User Contributed Notes 5 notes
If you like me have some trouble understanding example #1 due to the bitwise operator (&) used, here is an explanation.
The part in question is this callback function:
45 in binary: 101101
1 in binary: 000001
——
result: 000001
Some of PHP’s array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:
The array functions mentioned above allow you compose new functions on arrays.
This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.
E.g. a mathematician might state
map(f o g) = map(f) o map(g)
the so called «loop fusion» law.
Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).
I can’t get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.
My favourite use of this function is converting a string to an array, trimming each line and removing empty lines:
Depending on the intended meanings of your «empty» array values, e.g., null and empty string, vs. an integer 0 or a boolean false, be mindful of the result of different filters.
declare( strict_types = 1 );
array (size=3)
‘intzero’ => int 0
‘stringzero’ => string ‘0’ (length=1)
‘stringfalse’ => string ‘false’ (length=5)
array (size=5)
‘nullstring’ => string » (length=0)
‘intzero’ => int 0
‘stringzero’ => string ‘0’ (length=1)
‘false’ => boolean false
‘stringfalse’ => string ‘false’ (length=5)
array (size=4)
‘intzero’ => int 0
‘stringzero’ => string ‘0’ (length=1)
‘false’ => boolean false
‘stringfalse’ => string ‘false’ (length=5)
PHP: How to use array_filter() to filter array keys?
The callback function in array_filter() only passes in the array’s values, not the keys.
15 Answers 15
Since PHP 7.4 introduced arrow functions we can make this more succinct:
I needed to do same, but with a more complex array_filter on the keys.
Here’s how I did it, using a similar method.
This outputs the result:
Here is a more flexible solution using a closure:
So in the function, you can do other specific tests.
If you are looking for a method to filter an array by a string occurring in keys, you can use:
The result of print_r($mResult) is
An adaption of this answer that supports regular expressions
How to get the current key of an array when using array_filter
It passes the array you’re filtering as a reference to the callback. As array_filter doesn’t conventionally iterate over the array by increasing it’s public internal pointer you have to advance it by yourself.
What’s important here is that you need to make sure your array is reset, otherwise you might start right in the middle of it.
In PHP >= 5.4 you could make the callback even shorter:
Starting from PHP 5.6, you can use the ARRAY_FILTER_USE_KEY flag in array_filter :
Otherwise, you can use this function (from TestDummy):
And here is an augmented version of mine, which accepts a callback or directly the keys:
Last but not least, you may also use a simple foreach :
Here’s a less flexible alternative using unset():
The result of print_r($array) being:
This is not applicable if you want to keep the filtered values for later use but tidier, if you’re certain that you don’t.
array filter function from php:
For Example : Consider simple array
If you want to filter array based on the array key, We need to use ARRAY_FILTER_USE_KEY as third parameter of array function array_filter.
If you want to filter array based on the array key and array value, We need to use ARRAY_FILTER_USE_BOTH as third parameter of array function array_filter.