PHP Function of the Day (2011-9-26): array_filter

As with [fphp]array_walk[/fphp], [fphp]array_filter[/fphp] benefits immensely from the inclusion of callbacks in PHP 5.3 (the code below will not work in PHP 5.2 or earlier).


// Construct an array of the numbers 1 to 100 for our example.
$array = array();

for ($i = 1; $i < 100; $i++) {
  $array[] = $i;
}

// Now our example - filter out numbers divisible by 3.
$newArray = array_filter($array, function($s) {
  return $s % 3 == 0;
});

The filter must return true or false (Yes, you can return the results of a boolean calculation directly as in the example. Arithmetic operations come before boolean operations in the overall order of operations). It receives two arguments, the value of the segment (in this case $s) and the key of the array segment (Which wasn’t relevant to this callback so omitted).