php数组选择大于数字且低于另一数字的值并将其保存到新数组

Aki*_*isC 9 php arrays

我有一个包含以下数字的数组(动态创建)

$numbers = array (200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 12000, 14000, 15000, 16000, 18000, 20000, 21000, 24000, 25000, 27000, 30000, 35000, 40000, 45000, 50000, 60000, 70000, 75000, 80000, 90000, 100000, 105000, 120000, 135000, 140000, 150000, 160000, 180000, 200000, 250000, 300000, 350000, 400000, 450000, 500000, 600000, 700000, 800000, 900000, 1000000)
Run Code Online (Sandbox Code Playgroud)

我想通过> =和<=创建新数组(已过滤),例如新数组包含的数字大于或等于(> =)大于800且小于或等于(<=)大于1600

New Array
(
    [0] => 800
    [1] => 1000
    [2] => 1200
    [3] => 1400
    [4] => 1600
)
Run Code Online (Sandbox Code Playgroud)

是不是可以使用foreach?

Mar*_*ker 19

$min = 800;
$max = 1200;
$newNumbers = array_filter(
    $numbers,
    function ($value) use($min,$max) {
        return ($value >= $min && $value <= $max);
    }
);
Run Code Online (Sandbox Code Playgroud)


小智 7

您正在寻找array_filter http://php.net/manual/en/function.array-filter.php

使用的一个很好的例子是:

array_filter($numbers, function($n){ 
    return $n >= 800 && $n <= 1600;
});
Run Code Online (Sandbox Code Playgroud)