shashank
shashank

Reputation: 566

Find value lies between key in array in php

I have an array like this in php-

$array=array
(
    "0.00" => 1,
    "50.00" => 3,
    "75.00" => 2,
    "100.00" => 3,
    "120.00" => 1,
    "180.00" => 5,
    "200.00" => 6,
    "210.00" => 4,
    "220.00" => 2,
    "300.00" => 1,
    "500.00" => 7
);

I have to find values between 0-100 and 100-200, so my new array should look like this-

array{
  "0-100" => 9, // total values between 0 to 100 including value of 0 and 100
  "100-200" => 15,  // total values between 100 to 200 including value of 100 and 200 
  "200-300" => 13,  // same way
  "300-500" => 8  //same way
} 

How can I make this array.?

Upvotes: 1

Views: 187

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

Note that the use of ARRAY_FILTER_USE_KEY requires PHP >=5.6.0

$array=[
    "0.00" => 1,
    "50.00" => 3,
    "75.00" => 2,
    "100.00" => 3,
    "120.00" => 1,
    "180.00" => 5,
    "200.00" => 6,
    "210.00" => 4,
    "220.00" => 2,
    "300.00" => 1,
    "500.00" => 7
];

function filtered($array, $min, $max) {
    return array_sum(
        array_filter(
            $array,
            function($key) use ($min, $max) {
                return (($key >= $min) && ($key <= $max));
            },
            ARRAY_FILTER_USE_KEY
        )
    );
}

$newArray = [
    '0-100' => filtered($array, 0, 100),
    '100-200' => filtered($array, 100, 200),
    '200-300' => filtered($array, 200, 300),
    '300-400' => filtered($array, 300, 400),
];

var_dump($newArray);

EDIT

If you're not using PHP >= 5.6.0, then you can use

function filtered($array, $min, $max) {
    return array_sum(
        array_intersect_key(
            $array,
            array_flip(
                array_filter(
                    array_keys($array),
                    function($key) use ($min, $max) {
                        return (($key >= $min) && ($key <= $max));
                    }
                )
            )
        )
    );
}

instead

Upvotes: 2

Related Questions