Shaolin
Shaolin

Reputation: 2551

Remove items from array without looping

Is there a way to eliminate more than one items from array without looping through it ?

Eg: array(1,3,67, 78, 60 , 5, 34, 68); 

I want to remove items > 50 at once

Upvotes: 0

Views: 339

Answers (2)

silkfire
silkfire

Reputation: 26033

Sure, you can use array_filter:

$array = array_filter(array(1, 3, 67, 78, 60 , 5, 34, 68), function($element) {
                                                              return $element <= 50;
                                                           });

The callback function must return true for those items in the array that you want to keep.

Upvotes: 4

Giedrius
Giedrius

Reputation: 633

This is not possible to do without looping, however you can use array_filter() function in order to hide the loop

function remove($var) { return $var < 50; }
$data = array_filter($data, 'remove');

Upvotes: 3

Related Questions