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 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)
array_filter — Фильтрует элементы массива с помощью callback-функции
Описание
Список параметров
Возвращаемые значения
Возвращает отфильтрованный массив.
Список изменений
| Версия | Описание |
|---|---|
| 5.6.0 | Добавлен необязательный параметр flag и константы ARRAY_FILTER_USE_KEY и ARRAY_FILTER_USE_BOTH |
Примеры
Пример #1 Пример использования array_filter()
Результат выполнения данного примера:
Результат выполнения данного примера:
Пример #3 array_filter() с указанным flag
Результат выполнения данного примера:
Примечания
Если callback-функция изменяет массив (например, добавляет или удаляет элементы), поведение этой функции неопределено.
Смотрите также
User Contributed Notes 44 notes
In case you are interested (like me) in filtering out elements with certain key-names, array_filter won’t help you. Instead you can use the following:
Here is how you could easily delete a specific value from an array with array_filter:
array_filter remove also FALSE and 0. To remove only NULL’s use:
$af = [1, 0, 2, null, 3, 6, 7];
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.
be careful with the above function «array_delete»‘s use of the stristr function, it could be slightly misleading. consider the following:
?>
Which filters all keys with «db» or «smarty» as their name (including objects which have a reference to those variables). The output of the above in a test case I did is the following:
Array
(
[userdata] => Array
(
[sid] => a130e675d380e0e9fe47897922d719ac
[not_in_db] =>
[user_id] => 1
[session_id] => 154
[permissions] => 1
[username] => tester
)
[systemobjects] => Array
(
[db] => **filtered by function**
[smarty] => **filtered by function**
)
)
Hi all,
Here’s a function that will look trough an array, and removes the array member when the search string is found.
if needle is left empty, the function will delete the array members that have no value (this means if it’s empty).
NOTE: It rebuilds the array from scratch, so keys begin with 0, like you would create a new array.
Example:
$array = array(«John», «Doe», «Macy»);
$array = array_clean($array, «doe», false);
print_r($array);
would return:
array
(
[0] => John
[1] => Macy
)
Hopes this helps someone 🙂
The following function modifies the supplied array recursively so that filtering is performed on multidimentional arrays as well, while preserving keys.
array_filter may not be used as it does not modify the array within itself.
Read «callback» parameter note with understanding (as well as «converting to boolean» chapter). Keep in midn, that 0, both:
* integer: 0 and
* float: 0.00
evaluates to boolean FALSE! And therefore all array nodes, that have such value WILL ALSO BE FILTERED by array_filter(), with default call back. Unless you provide your own callback function, that will (for example) filter only empty strings and NULLs, but leave «zeros» untouched.
Some people (including me) might be surprised to find this out.
I was looking for a function to delete values from an array and thought I had found it in array_filter(), however, I *didn’t* want the keys to be preserved *and* I needed blank values cleaned out of the array as well. I came up with the following (with help from many of the above examples):
array_walk_recursive
array_walk_recursive — Рекурсивно применяет пользовательскую функцию к каждому элементу массива
Описание
Список параметров
Если требуется, чтобы функция callback изменила значения в массиве, определите первый параметр callback как ссылку. Тогда все изменения будут применены к элементам массива.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования array_walk_recursive()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 27 notes
Since this is only mentioned in the footnote of the output of one of the examples, I feel it should be spelled out:
* THIS FUNCTION ONLY VISITS LEAF NODES *
That is to say that if you have a tree of arrays with subarrays of subarrays, only the plain values at the leaves of the tree will be visited by the callback function. The callback function isn’t ever called for a nodes in the tree that subnodes (i.e., a subarray). This has the effect as to make this function unusable for most practical situations.
How to modify external variable from inside recursive function using userdata argument.
// result
// 11 : 1
// 12 : 1
// 2 : 1
// counter: 0
// result
// 11 : 1
// 12 : 2
// 2 : 1
// counter : 0
// result
// 11 : 1
// 12 : 2
// 2 : 3
// counter : 3
Unfortunately the PHP example given doesn’t do this. It actually took me a while to figure out why my function wasn’t changing the original array, even though I was passing by reference.
One other silly thing you might try first is something like this:
I use RecursiveIteratorIterator with parameter CATCH_GET_CHILD to iterate on leafs AND nodes instead of array_walk_recursive function :
The description says «If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference.» This isn’t necessarily helpful as the function you’re calling might be built in (e.g. trim or strip_tags). One option would be to create a version of these like so.
multidimensional array to single array
Array ( [0] => 2 [1] => 4 [2] => 2 [3] => 7 [4] => 3 [5] => 6 [6] => 5 [7] => 4 )
array_walk_recursive itself cannot unset values. Even though you can pass array by reference, unsetting the value in the callback will only unset the variable in that scope.
A simple solution for walking a nested array to obtain the last set value of a specified key:
I needed to add or modify values in an array with unknown structure. I was hoping to use array_walk_recursive for the task, but because I was also adding new nodes I came up with an alternate solution.
I decided to add to the previous PHP 4 compatible version of array_walk_recursive() so that it would work within a class and as a standalone function. Both instances are handled by the following function which I modified from omega13a at sbcglobal dot net.
The following example is for usage within a class. To use as a standalone function take it out of the class and rename it. (Example: array_walk_recursive_2)