将 switch 语句转换为 if only in PHP

convert switch statement to one if only in PHP

我正在尝试打印从 1 到 50 的数字。对于 3 的倍数,它应该打印 "multiple of 3"。对于 5 的倍数,它应该打印 "multiple of 5"。对于 3 和 5 的倍数,它应该打印 "multiple of 3 and 5 both" 对于其他数字,它应该打印那个数字。

我使用 switch 尝试了下面的代码,它工作正常。但我不能使用 switch、三元运算符或 else 语句。

下面是我的代码 -

function findMultiples($n)  
{  
    $three = 3; // To keep track of multiples of 3  
    $five = 5; // To keep track of multiples of 5

    for ($i = 1; $i <= $n; $i++)  
    {  
        switch ($i) {
        case $i%$three==0 and $i%$five==0:
            echo "multiple of 3 and 5 both";
            break;
        case $i%$three==0:
            echo "multiple of 3";
            break;
        case $i%$five==0:
            echo "multiple of 5";
            break;
        default:
            echo $i;
        }

        echo "<br/>";
    }  

}  

// Driver Code 
findMultiples(50);  //I am getting expected result.

我如何通过使用下面的 if 条件来获得这个结果

$printNumbers = "";

if (($i%$three==0 and $i%$five==0) or ($i%$three==0) or ($i%$five==0))    
{  
    $printNumbers = $i;
}  

echo $printNumbers;

有点奇怪的问题,但是如果你只需要一个 IF 那么你可以同时使用比较和赋值来实现它:

<?php
    function findMultiples($n) {
        $three = 3; // To keep track of multiples of 3
        $five = 5; // To keep track of multiples of 5

        for ($i = 1; $i <= $n; $i++) {
            if (($i % $three == 0 and $i % $five == 0 and $text = 'both 3 and 5') or ($i % $three == 0 and $text = '3') or ($i % $five == 0 and $text = '5') or ($text = 'none')) {
                echo $i.' is divided by '.$text;
            }
            echo '<br>';
        }
    }

    findMultiples(50);

输出:

1 is divided by none
2 is divided by none
3 is divided by 3
4 is divided by none
5 is divided by 5
6 is divided by 3
7 is divided by none
8 is divided by none
9 is divided by 3
10 is divided by 5
11 is divided by none
12 is divided by 3
13 is divided by none
14 is divided by none
15 is divided by both 3 and 5
16 is divided by none
17 is divided by none
18 is divided by 3
19 is divided by none
20 is divided by 5
21 is divided by 3
22 is divided by none
23 is divided by none
24 is divided by 3
25 is divided by 5
26 is divided by none
27 is divided by 3
28 is divided by none
29 is divided by none
30 is divided by both 3 and 5
31 is divided by none
32 is divided by none
33 is divided by 3
34 is divided by none
35 is divided by 5
36 is divided by 3
37 is divided by none
38 is divided by none
39 is divided by 3
40 is divided by 5
41 is divided by none
42 is divided by 3
43 is divided by none
44 is divided by none
45 is divided by both 3 and 5
46 is divided by none
47 is divided by none
48 is divided by 3
49 is divided by none
50 is divided by 5

如有需要,请随时更改打印的文本。