Using Switch Statement in PHP

Using Switch Statement in PHP

Problem Description:

I have to print the multiples of numbers 3 from 80 to 100 by using switch statement

echo "Print Numbers Using Switch Statement:<br>";

for ($i=3; $i <= 100 ; $i=$i+3) {

    switch ($i) {
        case "$i >= 80":
            echo $i. "<br>";
            break;

        case "$i <= 100":
            echo $i."<br>";
            break;
    }
}

Solution – 1

Switch does not work this way. The case must match the switch expression.

Change to

switch (true)

Also remove the quotes off the case expressions.

for ($i = 3; $i <= 100; $i += 3) {
    switch (true) {
        case $i >= 80 && $i <= 100:
            echo "$i<br>";
    }
}

If you want both statemens as each case you can do like this

for ($i = 3; $i <= 100; $i += 3) {
    switch (true) {
        case $i < 80:
            break;
        case $i <= 100:
            echo "$i<br>";
    }
}

Output

81
84
87
90
93
96
99

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject