How to remove integers in array less than X?

▼魔方 西西 提交于 2019-12-17 21:30:02

问题


I have an array with integers of values from 0 to 100. I wish to remove integers that are less than number X and keep the ones that are equal or greater than number X.


回答1:


A little ugly using the clunky create_function, but straight forward:

$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 whatever you want.




回答2:


Smarter than generating an array that is too big then cutting it down to size, I recommend only generating exactly what you want from the very start.

range() will do this job for you without the bother of an anonymous function call iterating a 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 Output:

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

Alternatively, if you truly, truly want to modify the input array that you have already generated, then assuming you have an indexed array you can use array_slice() to remove elements using X to target the starting offset and optionally preserve the 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 Output:

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,
)


来源:https://stackoverflow.com/questions/2619944/how-to-remove-integers-in-array-less-than-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!