A Loop
is a sequence of instructions set to be executed repeatedly until a certain preset condition is met. Once reaching this preset condition, the loop ends immediately.
The usefulness of loops in program codes can not be overemphasized. They are essentially the building blocks of automation and the conditional operations of any system.
Without a loop, a developer would have to basically hard-code the whole process, which is impossible.
In PHP, there are different loop structures in place, which come in handy based on the nature of what is to be done. Such loops include:
while
loopdo while
loopfor
loopswitch
statementsA switch
statement is a loop structure that allows a program code to choose the code to run from a wide range of available code, based on which condition is met.
A switch is most valued when there are a lot of optional code blocks needed to be chosen from. This is a feature that is not available in the loop structures.
A switch statement will have a basic syntax, as shown below:
switch (x) {
case CaseName1:
//run code if x=CaseName1;
break;
case CaseName2:
//run code if n=CaseName2;
break;
case CaseName3:
//run code if n=CaseName3;
break;
...
default:
//run code where n is different from all CaseName;
}
We create and evaluate a single expression (x)
, usually a variable.
There is a comparison of the evaluated value of (x)
with the value of each case (CaseName 1-3)
in the switch statement.
If a matching value is found from any of the cases, the code to be executed in such a case is run.
With the break
keyword, the automatic continuation of the code execution to the next case is prevented. This means the comparison ends.
The default
will be the block to be executed when no match exists or was found among the cases.
A simple switch
case statement is shown in the code snippet below.
<?php$weekday = "wednesday";switch ($weekday) {case "monday":echo "Today is monday!";break;case "tuesday":echo "Today is tuesday!";break;case "wednesday":echo "Today is wednesday!";break;case "thursday":echo "Today is thursday!";break;default:echo "Happy weekend!";}?>
In the code snippet above, we see the following:
In line 2, a variable $weekday
has the string value wednesday
.
The value of $weekday
is compared to all the case values, which are monday
, tuesday
, wednesday
and thursday
on lines 5, 8, 11 and 14, respectively. If a match is found on any of the lines, the code block indicated in that case will be executed and the comparison will be stopped at that point, because of the break command.
On lines 17 and 18, we have the default block, which will run if all of the comparisons fail to execute.
Note: The comparison between string values is case-sensitive in a switch statement. For example, in the code above,
Wednesday
in any of the cases won’t match withwednesday
, as indicated in the$weekday
variable.