如何检查php中的倍数以抽象以下数字序列

时间:2014-10-13 20:05:41

标签: php

我有一个for循环,我想编写一个函数来抽象以下序列:

1   2   3   4
5   6   7   8
9   10  11  12
13  14  15  16
.............

因此,在某种“伪”代码中,函数必须像这样检查倍数:

$i = 0;

for (condition) {
    $i++

    if ($i is 1, 5, 9, 13) do something
    if ($i is 2, 6, 10, 14) do something
    if ($i is 3, 7, 11, 15) do something
    if ($i is 4, 8, 12, 16) do something
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用模运算符。 1,5,9或13模4总是1。

此外,您可能需要使用开关/ case语句,以避免重复模4部分。

<?php
switch ($remainder = $i % 4) {
    case 0:
        // and do another thing too
    break;
    case 1:
        // do something
    break;
    case 2:
        // do something else
    break;
    case 3:
        // do yet another thing
    break;

    default:
        throw new \UnexpectedValueException(sprintf(
            'the remainder is %d, this is very strange!',
            $remainder
        ));
}