Repeat number at each count

Asked

Viewed 34 times

0

How do I do this in php, please help me:

( Every three times )

0 = 0
1 = 0
2 = 0

3 = 1
4 = 1
5 = 1

6 = 2
7 = 2
8 = 2

So on and so forth. This is a simple example of what I would like to do, because I would actually like to implement a process distribution menu where there are 2 coordinators and a director, but to simplify I gave this simple example above.

1 answer

0


I leave below a javascript solution to be testable here on the site. The idea is to use the operator % (module) to check when incrementing the variable that is to the right of the equality, the module will be equal to 0 only in the multiples of the desired interval, for example if the interval is 3, the module of i shall be equal to 0 when i will be 3, 6, 9 ... See here more explanations about the module calculation if you are not familiar with it.

let repetir = 9, 
    current = -1,
    intervalo = 3;

for(let i = 0; i < repetir; i++){
  if(i % intervalo === 0)
    current++;
    
  console.log(`${i} = ${current}`);
}

And here the translation of the same in PHP:

$repetir = 9;
$current = -1;
$intervalo = 3;

for($i = 0; $i < $repetir; $i++){
  if($i % $intervalo == 0)
    $current++;
    
    echo "$i = $current <br />";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.