user217562
user217562

Reputation: 1567

How can I make an array of integers fit within a range?

Just say I want to take an array of numbers:

$a['a'] = 10;
$a['b'] = 20;
$a['c'] = 500;
$a['d'] = 1000;

And force them to fit within a range (e.g. 1 to 100) like so:

$a['a'] = 1;
$a['b'] = 2;
$a['c'] = 50;
$a['d'] = 100;

Another example...

From:

$a['a'] = 12;
$a['b'] = 28;

To:

$a['a'] = 1;
$a['b'] = 100;

What's the best way to go about it?

Upvotes: 1

Views: 2183

Answers (2)

Petah
Petah

Reputation: 46040

Update:

Now I understand what you actually want, you need to use this formula:

       (new_max - new_min)(x - min)
f(x) = ----------------------------  + new_min
                max - min

E.g.:

$a = [
    'a' => 10,
    'b' => 20,
    'c' => 500,
    'd' => 1000,
];
$min = min($a);
$max = max($a);
$new_min = 1;
$new_max = 100;
foreach ($a as $i => $v) {
    $a[$i] = ((($new_max - $new_min) * ($v - $min)) / ($max - $min)) + $new_min;
}
var_dump($a);

Example: http://codepad.viper-7.com/hwGnhJ


Old answer:

You can use array_walk, and min/max for that:

$a = [1, 2, 1000];
array_walk($a, function(&$value) {
    $value = max(min($value, 100), 1);
});
var_dump($a);

Example: http://codepad.viper-7.com/jjOCjx

Or just a simple foreach and if:

foreach ($a as $i => $v) {
    if ($v > 100) $a[$i] = 100;
    elseif ($v < 1) $a[$i] = 1;
}

Upvotes: 7

Praveen kalal
Praveen kalal

Reputation: 2129

Hi you can do this in following manner.

$a['a'] = 10;
$a['b'] = 20;
$a['c'] = 500;
$a['d'] = 1000; 

$range =10; // you can define the range here which you want.


foreach($a as $k=>$v)
{

    $a[$k] = $v/$range;

}

print_r($a);

Upvotes: 0

Related Questions