PhpStorm 2019.3 Help

Code Inspection: 'array_filter' can be converted to loop

Reports the array_filter calls that can be replaced with the foreach loop.

The array_filter (php.net) function is used for filtering array elements by using a callback function. You can also use a foreach loop (php.net) to achieve the same result.

In the following example, the myArr array's odd values are filtered out by using the odd callback function. The function is called from either the array_filter function call or the foreach loop.

array_filter() call

foreach loop

function odd($var) { return $var & 1; } $myArr = [1,2,3,4,5,6]; $filteredArr = array_filter($myArr, "odd");
function odd($var) { return $var & 1; } $myArr = [1, 2, 3, 4, 5, 6]; $array_filter = []; foreach ($myArr as $key => $var) { if (odd($var)) { $array_filter[$key] = $var; } } $filteredArr = $array_filter;
Last modified: 10 February 2020