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)
Поделиться
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.
filter_var_array
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
filter_var_array — Принимает несколько переменных и, при необходимости, фильтрует их
Описание
Список параметров
Массив со строковыми ключами, содержащий данные для фильтрации.
Этот параметр также может быть целым числом, содержащим предопределённую константу фильтра. Затем все значения во входном массиве фильтруются этим фильтром.
Возвращаемые значения
Примеры
Пример #1 Пример использования filter_var_array()
//OUTPUT:
//formarray(3) < [0]=>string(4) «bold» [1]=> string(10) «javascript» [2]=> string(26) «P*>i@893746%%%p*.i.*>>|.dw» >
?>
$emails = [
‘a’ => ’email1@domain.com’,
‘b’ => ‘ @domain.com’,
];
$result = filter_var_array($emails, FILTER_SANITIZE_EMAIL);
print_r($result);
// the result will be.
// array(‘a’ => ’email1@domain.com’, ‘b’ => ’email2@domain.com’)
for those who would like to know how to use regular expressions with filter var array. taken from w3 schools.
‘filter’=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING,
‘options’=>array(‘regexp’=>»/^michael$/»),
var_dump($output); // array(1) < ["regxp"]=>string(7) «michael» >
an update to previous post.
using regular expressions along with another filter in filter var array
‘filter’=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING,
‘flags’=>FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK,
‘options’=>array(‘regexp’=>»/t(.*)/»),
var_dump($output); // array(1) < ["regxp"]=>string(3) «caf» >
array_filter
array_filter — Фильтрует элементы массива с помощью callback-функции
Описание
Список параметров
Возвращаемые значения
Возвращает отфильтрованный массив.
Примеры
Пример #1 Пример использования array_filter()
Результат выполнения данного примера:
Результат выполнения данного примера:
Примечания
Если callback-функция изменяет массив (например, добавляет или удаляет элементы), поведение этой функции неопределено.
Смотрите также
Коментарии
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:
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
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.