Skip to content

Instantly share code, notes, and snippets.

@balsama
Created June 9, 2022 14:11
Show Gist options
  • Save balsama/444869bdeee087d05ed8185f4a3c873d to your computer and use it in GitHub Desktop.
Save balsama/444869bdeee087d05ed8185f4a3c873d to your computer and use it in GitHub Desktop.
Function to convert a value in a range to an equivalent value in a different range.
<?php
function rangeConverter(
int $input,
int $inputRangeMin,
int $inputRangeMax,
int $outputRangeMin = 0,
int $outputRangeMax = 100
) :int
{
if ($inputRangeMax <= $inputRangeMin) {
throw new \http\Exception\InvalidArgumentException('$inputRangeMax must be greater than $inputRangeMin');
}
if ($outputRangeMax <= $outputRangeMin) {
throw new \http\Exception\InvalidArgumentException('$outputRangeMax must be greater than $outputRangeMin');
}
if ($input < $inputRangeMin) {
throw new \http\Exception\InvalidArgumentException('$input must be greater than $inputRangeMin');
}
if ($input > $inputRangeMax) {
throw new \http\Exception\InvalidArgumentException('$input must be less than $inputRangeMax');
}
return (
($outputRangeMax - $outputRangeMin)
*
(
($input - $inputRangeMin)
/
($inputRangeMax - $inputRangeMin)
)
)
+
$outputRangeMin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment