Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php numeric array select values greater than a number and lower than another and save it to a new array

Tags:

arrays

php

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?

like image 987
AkisC Avatar asked Apr 02 '13 23:04

AkisC


People also ask

What does => mean in PHP array?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .

Can PHP array store different types of data?

You can store anything you want in an array.

How do you write associative array in PHP?

Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.

How do you get a specific value from an array in PHP?

1. PHP array_search() function. The PHP array_search() is an inbuilt function that is widely used to search and locate a specific value in the given array. If it successfully finds the specific value, it returns its corresponding key value.


2 Answers

$min = 800;
$max = 1200;
$newNumbers = array_filter(
    $numbers,
    function ($value) use($min,$max) {
        return ($value >= $min && $value <= $max);
    }
);
like image 120
Mark Baker Avatar answered Oct 23 '22 06:10

Mark Baker


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;
});
like image 12
Unseen Revolution Avatar answered Oct 23 '22 06:10

Unseen Revolution