Last Updated: February 25, 2016
·
1.102K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#php
#array
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside