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
Written by Akhyar A.
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#