Last Updated: February 25, 2016
·
743
· akhyar

A clean way to filter array in PHP

Rather than looping through an array and 'unset'-ing certain indices, PHP offers a cleaner way to do this.

For example, you have array like this:

$nums = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

To get rid of even numbers (thus, keeping the odd ones) you can simply use array_filter combined with an anonymous function.

$odds = array_filter($nums, function($var){
    return $var % 2 == 1; 
    // keep the value if TRUE 
});

The $odds array will contains only odd numbers: 1, 3, 5, 7, 9