Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - map a value using fromRange and toRange?

I'm trying to figure out how to map a number between 1 and 1000 to a number between 1 and 5.

For example:

I have a database of 1000 records and I want to assign an id number between 1 and 5 to each record. I don't want it to be random, thats easy enough with rand(1,5).

In the Arduino language it has a function that I'm hoping PHP has:

result = map(value, fromLow, fromHigh, toLow, toHigh)

The purpose of this is I don't want to store that mapped value in the database, I need a php function that I can call and if say the db record is 100 no matter how often the function is called it will always return the same mapped value.

Thanks!

like image 328
Joe Avatar asked Aug 30 '26 16:08

Joe


2 Answers

The function you're looking for maps ranges by using different scales. So that's easy to do:

function map($value, $fromLow, $fromHigh, $toLow, $toHigh) {
    $fromRange = $fromHigh - $fromLow;
    $toRange = $toHigh - $toLow;
    $scaleFactor = $toRange / $fromRange;

    // Re-zero the value within the from range
    $tmpValue = $value - $fromLow;
    // Rescale the value to the to range
    $tmpValue *= $scaleFactor;
    // Re-zero back to the to range
    return $tmpValue + $toLow;
}

So basically, it'll re-base the number within the range. Now, note that there is no error checking if value is within either range. The reason is that it maps scales, not ranges. So you can use it for base conversion:

$feet = map($inches, 0, 12, 0, 1);

And you can map "ranges" as well since it re-bases the number (moves it along the number line):

5 == map(15, 10, 20, 0, 10);

So for from range (0, 1000) and to range (0, 5), the following table will hold true:

  • -200 | -1
  • 0 | 0
  • 1 | 0.005
  • 100 | 0.5
  • 200 | 1
  • 400 | 2
  • 600 | 3
  • 800 | 4
  • 1000 | 5
  • 2000 | 10
  • 3000 | 15

And to show the re-basing, if we map (0, 1000) to (5, 10):

  • -200 | 4
  • 0 | 5
  • 1 | 5.005
  • 100 | 5.5
  • 200 | 6
  • 400 | 7
  • 600 | 8
  • 800 | 9
  • 1000 | 10
  • 2000 | 15
  • 3000 | 20
like image 146
ircmaxell Avatar answered Sep 02 '26 05:09

ircmaxell


Have you considered: $mappedValue = ($value % 5) + 1;? Will return the remainder after dividing the value by 5 (i.e. 0-4) then adds one.

like image 39
daiscog Avatar answered Sep 02 '26 05:09

daiscog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!