PHP 8.6: array_filter function's $mode throws ValueError on invalid values
The array_filter function in PHP filters an array using a callback function. It supports an optional $mode parameter that accepts an integer value to specify whether the array key, value, or both should be passed to the callback function.
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
The $mode parameter only accepts three values:
0(default): Pass the array value as the only parameter to$callback.ARRAY_FILTER_USE_BOTH(assigned1): Pass both array value and key to$callback.ARRAY_FILTER_USE_KEY(assigned2): Pass the array key to$callback.
New ARRAY_FILTER_USE_VALUE Constant
Since the default value (0) of the array_filter function is not defined as a PHP constant, PHP 8.6 declares a new global constant named ARRAY_FILTER_USE_VALUE. This constant is assigned value 0, which is the same as the default value for the $mode parameter.
const ARRAY_FILTER_USE_VALUE = 0;
Passing Unrecognized $mode throws a ValueError
In PHP 8.6 and later, passing a value other than ARRAY_FILTER_USE_VALUE (0), ARRAY_FILTER_USE_BOTH (1), or ARRAY_FILTER_USE_KEY (2) throws a ValueError exception.
array_filter([], fn() => true, 3);
ValueError: array_filter(): Argument #3 ($mode) must be one of ARRAY_FILTER_USE_VALUE, ARRAY_FILTER_USE_KEY, or ARRAY_FILTER_USE_BOTH.
Backward Compatibility Impact
Prior to PHP 8.6, if an unrecognized value was passed to the array_filter function's $mode parameter, it is silently ignored, and the function behaves as if $mode = 0.
In PHP 8.6 and later, passing an invalid value throws a ValueError exception.
The ARRAY_FILTER_USE_VALUE constant is new, but it can be trivially polyfilled on older PHP versions:
if (!defined('ARRAY_FILTER_USE_VALUE')) {
define('ARRAY_FILTER_USE_VALUE', 0);
}