Recipe 4.13. Finding Elements That Pass a Certain Test


4.13.1. Problem

You want to locate entries in an array that meet certain requirements.

4.13.2. Solution

Use a foreach loop:

$movies = array(...); foreach ($movies as $movie) {     if ($movie['box_office_gross'] < 5000000) { $flops[] = $movie; } }

Or array_filter( ):

$movies = array(...); function flops($movie) {     return ($movie['box_office_gross'] < 5000000) ? 1 : 0; } $flops = array_filter($movies, 'flops');

4.13.3. Discussion

The foreach loops are simple: you iterate through the data and append elements to the return array that match your criteria.

If you want only the first such element, exit the loop using break:

foreach ($movies as $movie) {     if ($movie['box_office_gross'] > 200000000) { $blockbuster = $movie; break; } }

You can also return directly from a function:

function blockbuster($movies) {     foreach ($movies as $movie) {         if ($movie['box_office_gross'] > 200000000) { return $movie; }     } }

With array_filter( ), however, you first create a callback function that returns TRue for values you want to keep and false for values you don't. Using array_filter( ), you then instruct PHP to process the array as you do in the foreach.

It's impossible to bail out early from array_filter( ), so foreach provides more flexibility and is simpler to understand. Also, it's one of the few cases in which the built-in PHP function doesn't clearly outperform user-level code.

4.13.4. See Also

Documentation on array_filter( ) at http://www.php.net/array-filter.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net