Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "map" function in php?

Tags:

php

range

map

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);
like image 698
functionvoid Avatar asked Jun 20 '12 16:06

functionvoid


People also ask

What is the use of map function in PHP?

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.

What are the 3 types of PHP arrays?

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.

What is an ordered map in PHP?

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).

What is array and map?

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.


2 Answers

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.

like image 107
FtDRbwLXw6 Avatar answered Oct 07 '22 06:10

FtDRbwLXw6


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;
}
like image 21
Bernz Avatar answered Oct 07 '22 07:10

Bernz