Функция перебирает массив array
и передаёт каждое значение в callback-функцию.
Текущее значение массива array копируется в массив (array) с результатами,
если callback-функция возвращает true.
Функция сохраняет ключи входного индексного массива array,
поэтому после фильтрации иногда появляются пропуски.
Массив (array) с результатами переиндексируют функцией array_values().
Функция удалит пустые элементы входного массива array,
если callback-функцию не передали. Описание
языковой конструкции empty() рассказывает,
как PHP определяет пустые элементы.
mode
Флаг определяет, какие аргументы передавать в callback-функцию:
ARRAY_FILTER_USE_KEY —
вместо значения массива как единственного аргумента
callback-функции передавать только ключ массива.
ARRAY_FILTER_USE_BOTH —
вместо значения массива как единственного аргумента
callback-функции передавать и значение — первым аргументом,
и ключ массива — вторым аргументом.
Значение по умолчанию равно 0,
с которым в callback-функцию передаётся
только значение массива.
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:
<?php function odd($var) { // returns whether the input integer is odd return($var & 1); } ?>
If given an integer this function returns the integer 1 if $var is odd and the integer 0 if $var is even. The single ampersand, &, is the bitwise AND operator. The way it works is that it takes the binary representation of the two arguments and compare them bit for bit using AND. If $var = 45, then since 45 in binary is 101101 the operation looks like this:
45 in binary: 101101 1 in binary: 000001 ------ result: 000001
Only if the last bit in the binary representation of $var is changed to zero (meaning that the value is even) will the result change to 000000, which is the representation of zero.
It is clearly documented above, but make sure you never forget that when ARRAY_FILTER_USE_BOTH is set, the callback argument order is value, key - NOT key, value. You'll save some time.
Functional programming is a paradigm which centers around the side-effect free evaluation of functions. A program execution is a call of a function, which in turn might be defined by many other functions. One idea is to use functions to create special purpose functions from other functions.
The array functions mentioned above allow you compose new functions on arrays.
E.g. array_sum = array_map("sum", $arr).
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.
Although it states clearly that array keys are preserved, it's important to note this includes numerically indexed arrays. You can't use a for loop on $array above without processing it through array_values() first.
The fact that array_filter preserves keys makes partitioning an array into [elements that pass the test, elements that fail the test] quite easy. In essence:
The array_diff_key call is key; indexing the returned array as shown allows lines like "$failures = $partition[false];" to do the right thing (the booleans get converted to integers of course, but it's consistent and self-documenting).