Convert the iteration number to a limited range (e.g. day of the week)

I need to translate the iteration number to a range from 1 to 7.

$y = keepInRange(1, 7, $i)

The expected result of input → output, as follows

  • 1 → 1
  • ...
  • 7 → 7
  • 8 → 1
  • 9 → 2
  • ...
  • 14 → 7
  • 15 → 1

I have already tried the following without success:

min(7, max(1, $numberToStr[$i])) (all output 1)
$y = $i % 7 (all outputs 0, Edit: this was a mistake by me, its the solution when +1 is added.)
+4
source share
2 answers

try it

<?php
$num = 15;
$res= $num%7;
if($res == 0)
{
    echo "7";
}
else
{
    echo $res;
}

https://3v4l.org/dDGs3

I hope it will be useful

+2
source

Try:

$day_of_week = $num <= 7 ? $num : $num % 7;

Demo:

for($num=1; $num<25; $num++) {
    $day_of_week = $num <= 7 ? $num : $num % 7;
    echo '<p>'.$num.': '.$day_of_week.'</p>';
}

Demo in JS .

+2
source

All Articles