15

I have one array(dynamically created) that contains the following numbers

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

I want to create new array (filtered) by >= and <= for example the new array to contains numbers greater or equal(>=) than 800 and lower or equal(<=) than 1600

New Array
(
    [0] => 800
    [1] => 1000
    [2] => 1200
    [3] => 1400
    [4] => 1600
)

is that possible without using foreach?

3
  • array_filter() with a callback Commented Apr 2, 2013 at 23:13
  • 1
    ^ array_filter($numbers, function($n){ return $n >= 800 && $n <= 1600 } Commented Apr 2, 2013 at 23:14
  • yes! I did not know it how to pass two variables to array_filter. thanks both of you! Commented Apr 2, 2013 at 23:17

2 Answers 2

29
$min = 800;
$max = 1200;
$newNumbers = array_filter(
    $numbers,
    function ($value) use($min,$max) {
        return ($value >= $min && $value <= $max);
    }
);
Sign up to request clarification or add additional context in comments.

3 Comments

@CJDennis - the significant difference is that "use" variable values ($min and $max) are fixed (and so must exist) at the point where the anonymous/lambda function is defined, whereas normal arguments (in this case $value) are passed when the function is called.... it doesn't make much difference in this case, but may in other cases
The other difference is that the callback for array_filter() accepts only a specific argument or argument set (you can pass the key as well in recent versions of PHP), so you need to use use in that case to pass additional arguments to the function
I've been wondering how to pass extra variables to lambda functions and now I know!
12

You are looking for array_filter http://php.net/manual/en/function.array-filter.php

A good example of use would be:

array_filter($numbers, function($n){ 
    return $n >= 800 && $n <= 1600;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.