Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

array_filter()

Synopsis

    array array_filter ( array arr [, function callback] )

The array_filter() allows you to filter elements through a function you specify. If the function returns true, the item makes it into the array that is returned; otherwise, it does not. For example:

    function endswithy($value) {
            return (substr($value, -1) =  = 'y');
    }

    $people = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Joe");
    $withy = array_filter($people, "endswithy");
    var_dump($withy);
    // contains "Johnny", "Timmy", "Bobby", and "Tammy"

In this script, we have an array of people, most of whom have a name ending with "y". However, several do not, and we want to have a list of people whose names ends in "y", so array_filter() is used. The function endswithy() will return true if the last letter of each array value is a "y"; otherwise, it will return false. By passing that as the second parameter to array_filter(), it will be called once for every array element, passing in the value of the element as the parameter to endswithy(), where it is checked for a "y" at the end.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page