Filtering your array through a function

array array_filter ( array input [, callback function])

The final array function in this group is array_filter(), which is a very powerful function that 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 is not. Consider this script:

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

    $people = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe");
    $withy = array_filter($people, "endswithy");
    var_dump($withy);
?>

In this script we have an array of people, most of which have a name ending with "y". However, several do not, and for one reason or another 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 ends with a y, otherwise 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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Converting an array to individual variables >>

Previous chapter: Stripping out duplicate values

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.