How to remove integers in an array less than X?

I have an array with integers from 0 to 100. I want to remove integers that are less than the number X, and keep those that are equal to or greater than the number X.

+6
arrays php integer filtering
source share
2 answers

A bit ugly using the clumsy create_function , but bluntly:

 $filtered = array_filter($array, create_function('$x', 'return $x >= $y;')); 

For PHP> = 5.3:

 $filtered = array_filter($array, function ($x) { return $x >= $y; }); 

Set $y to what you want.

+13
source share

Smarter than creating an array that is too large, but reducing it to size, I recommend only generating exactly what you want from the start.

range() will do the job for you without worrying about the anonymous function, iterating with the condition.

Code: ( Demo )

 $rand=rand(0,100); // This is your X randomly generated echo $rand,"\n"; $array=range($rand,100); // generate an array with elements from X to 100 (inclusive) var_export($array); 

Potential yield:

 98 array ( 0 => 98, 1 => 99, 2 => 100, ) 

Alternatively, if you really want to change the original array that you already generated, then assuming you have an indexed array, you can use array_slice() to delete elements with X to set the initial offset and, if necessary, save indexes / keys.

Code: ( Demo )

 $array=range(0,100); $rand=rand(0,100); // This is your X randomly generated echo $rand,"\n"; var_export(array_slice($array,$rand)); // reindex the output array echo "\n"; var_export(array_slice($array,$rand,NULL,true)); // preserve original indexes 

Potential yield:

 95 array ( 0 => 95, 1 => 96, 2 => 97, 3 => 98, 4 => 99, 5 => 100, ) array ( 95 => 95, 96 => 96, 97 => 97, 98 => 98, 99 => 99, 100 => 100, ) 
0
source share

All Articles