skip to Main Content

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?

3

Answers


  1. Divide the number by 5 and get the integer part. For example 7/5=1.4. Then multiply it by the integer part by 5 1×5=5. Then add 5 and you will see that it is in the range of 5-10. 19/5=3.8 3×5=15 15+5=20 In the range of 15-20. You can do this for other ranges as well.

    Login or Signup to reply.
  2. You can use the floor() function to find the previous or next numbers you need. With floor($value / $fixed) you get a number smaller or greater than $fixed (except you use a multiple of $fixed). This number x $fixed then is your previous number. When you add $fixed to that number, you have the greater number.

    $fixed = 5;
    $value = 7;
    
    $smaller = floor($value / $fixed) * $fixed;
    $greater = $smaller + $fixed;
    
    Login or Signup to reply.
  3. 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:

    • since you may need this multiple times, we avoid duplicating the same pattern in the code and create a function (or a method) instead
    • we want to find the range of the $value passed to this function
    • you want ranges of $moduloClass, so $value will be equal to the greatest number divisible with $moduloClass. The reason why I made this a parameter is to allow you to choose other range sizes too if needed
    • yet, the default for $moduloClass is 5, so if you do not pass a value for this parameter, it will be assumed to be 5
    • We compute the remainder of the division of $value to $moduloClass and subtract the result from $value. If $value is 7 and $moduloClass is 5, then $value % $moduloClass is 2 and $value - 2 is 7 – 2 = 5, so this will be assigned to $start
    • $end will equal to $start + $moduloClass, so if $start was 5, then $end will be 10
    • we return an array, whose start key will be the start of the range and end key will be the end of the range

    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]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search