I am trying to find a php equivalent of processing's "map" function so I can re-map a number from one range to another. Does anything exist? Is it called something different?
http://processing.org/reference/map_.html
For example to map a value from 0-100 to 0-9.
map(75, 0, 100, 0, 9);
The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. Tip: You can assign one array to the function, or as many as you like.
In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
A map is sometimes called ordered when the entries remain in the same sequence in which they were inserted. For example, arrays in PHP are ordered (preserve insertion order).
Definition and Usagemap() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
There is no native function for doing this, but it's easy to create:
function map($value, $low1, $high1, $low2, $high2) {
return ($value / ($high1 - $low1)) * ($high2 - $low2) + $low2;
}
This is untested, but you should hopefully get the idea.
Thanks for this great function!
I would personally improve a bit this function by adding simple error checking, to avoid dividing by 0, which would make PHP have a fatal error.
function map($value, $low1, $high1, $low2, $high2) {
if ($low1 == $high1)
return $low1;
return ($value / ($high1 - $low1)) * ($high2 - $low2) + $low2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With