Flashmark

Avatar

Filtering array elements in PHP using a array_filter and an anonymous callback function

There’s been a few times when i’ve used PHP’s array_filter() function to filter out some array elements - and I regularly find that I want to pass a parameter to the callback function which will affect the filter results. Unfortunately, this can’t be done with the callback implementation! This is the technique I use to achieve the same effect.

I am suprised that PHP’s implementation of callback functions does not support passing arbitrary parameters, especially since methods of a class / object can be referenced as callback functions by passing an array with the object / class name at index 0 and the method name at index 1.

I’ll normally use this technique when i’m calling array_filter() from within a loop - and I need to filter the array based on some variable which changes on each iteration of the loop. I’d like to pass this variable as a parameter to the callback function, but array_filter() will only pass the current array element to the callback function, so we need to achieve it in another way.

The solution I employ is to create an anonymous function during each loop iteration, using PHP’s create_function(). This creates a function at runtime, from the parameters passed in. We can pass the function definition (i.e. the PHP code) as a string, and use variables, much the same as you would when outputting dynamic variables in HTML output.

Here’s an example:

<?php
// Students and their grade results
$results = array(
 0 => array('name' => 'John Doe',  'grade' => 'A'),
 1 => array('name' => 'Jane Doe',  'grade' => 'A'),
 2 => array('name' => 'Jim Doe',   'grade' => 'B'),
 3 => array('name' => 'Paul Doe',  'grade' => 'C'),
 4 => array('name' => 'Peter Doe', 'grade' => 'C')
);
// We want to know how many strudents achieved each grade.
$grades = array('A','B','C');
foreach($grades as $grade)
{
 // Create anonymous callback function to filter results for this grade.
 $function_body = 'return ( $input[\'grade\'] == "'.$grade.'" );';
 $function_name = create_function('$input', $function_body);
 
 // Filter the results array using the anonymous callback function.
 $filtered_results = array_filter($results, $function_name);
 
 // Write some output.
 echo "students achieving grade $grade: ".count($filtered_results)."<br >\n";
}
?> 

This will output the following:

students achieving grade A: 2
students achieving grade B: 1
students achieving grade C: 2 

There you have it, how to implement an anonymous callback function to be used to filter an array.

No Comments, Comment or Ping

Reply to “Filtering array elements in PHP using a array_filter and an anonymous callback function”