好吧,$i 将从1 迭代到5,这意味着您可以创建另一个变量$j,它等效于$i + 2,但当然它会导致计数:
3, 4, 5, 6, 7
取模运算符 (%) 出现在哪里,取模运算符给出除以第二个数后的余数:
3 % 5 //3
7 % 5 //2
如果您从 1 迭代到 5 并添加 2 (3-7),并获取结果 mod(5),您会得到:
方程:
$j = ($i + 2) % 5
3, 4, 0, 1, 2
这与您想要的很接近,但并不完全。所以不是最初添加2,而是最初添加1,然后在模数结果之后再次添加:
$j = $i;
$j += 1;
$j %= 5;
$j += 1;
//or in one line:
$j = (($i + 1) % 5) + 1;
这会给你一系列3, 4, 5, 1, 2。
要使用随机偏移量,只需确保初始填充在一组 5 个连续正整数中随机化:
//this could be rand(0, 4) or rand(101, 105)
//it doesn't actually matter which range of 5 integers
//as the modulus operator will bound the results to the range of 0-4
$offset = rand(1, 5);
for ($i = 1; $i <= 5; $i++) {
$j = (($i + $offset) % 5) + 1;
}