phpmath

How to set a dynamic range by fixed number


I am trying to set a range by a fixed number for an example.

$fixed = 5;
$value = 7;

So if my value is 7 it will be in a range from 5 to 10

I was trying the old fashion method to add + 5 to the value, but it goes out of the range. (7 + 5 = 12) and it has to be in range between 5 to 10.

$value = 19; // range in 15 to 20
$value = 23; // range in 20 to 25

Any idea?


Solution

  • This is how you can get such ranges:

    function getRange(int $value, int $moduloClass = 5) {
        $start = $value - ($value % $moduloClass);
        $end = $start + $moduloClass;
        return [
            'start' => $start,
            'end' => $end
        ];
    }
    

    Explanation:

    Example1

    $range = getRange(7); //$moduloClass is defaulting to 5
    echo "[" . $range['start'] . ", " . $range['end'] . "]";
    //result will be [5, 10]
    

    Example2

    $range = getRange(345, 100);
    echo "[" . $range['start'] . ", " . $range['end'] . "]";
    //result will be [300, 400]