-2

Let's say I have this array of numbers:

$arr = [100, 60, 30, 22, 1]

and it's based off a 1 - 100 range. And I want it based of a 1 - 5 range.

I have found this answer here: How to scale down a range of numbers with a known min and max value which details:

Array.prototype.scaleBetween = function(scaledMin, scaledMax) {
  var max = Math.max.apply(Math, this);
  var min = Math.min.apply(Math, this);
  return this.map(num => (scaledMax-scaledMin)*(num-min)/(max-min)+scaledMin);
}

But I am not sure how I would translate that to PHP/Laravel.

test
  • 17,706
  • 64
  • 171
  • 244

1 Answers1

3

Not sure if this are the correct results, but it does what you described:

$arr = [100, 60, 30, 22, 1];

function scale(array $array, float $min, float $max): array
{
    $lowest = min($array);
    $highest = max($array);

    return array_map(function ($elem) use ($lowest, $highest, $min, $max) {
        return ($max - $min) * ($elem - $lowest) / ($highest - $lowest) + $min;
    }, $array);
}

echo json_encode(scale($arr, 1, 10));
// [10,6.363636363636363,3.6363636363636362,2.909090909090909,1]
Namoshek
  • 6,394
  • 2
  • 19
  • 31