softwarewebsites

PHP: Switch Statement

What is Switch statement in PHP and how to use it? This is the common questions over the internet.
In the previous article that been written we learn the different various types of statement that can able us to create a simple program in PHP.
In this article we will learn on how to use switch statement in our program. Switch statement can also serves as a conditional statement.
It can check every conditions in our program at once. Though switch statement can be use as a conditional statement
but still it has different way of how does it works. Switch statement works only with a single variable on it. Then with that single variable as an input it checks all the cases in the switch statement.
Unlike with IF statement that every condition the program must have to read it.
Switch statement perform that condition all at once. In order for us to know how to declare or to know what is the simple illustration on how to use switch below is an illustration that we can follow.
Illustration:Variable_name = “value”; Switch(variable name) { Case “condition 1”: Execute statement here…… Break; Case “condition 2”: Execute statement here…… Break; }

Above is the sample format on how to use to switch statement.

Very simple, we only have to declare the variable first with its value then after which we have now to use the switch keyword inside of its parentheses is the variable name.
Then to perform the condition we have 2 different cases below which are the condition 1 and condition 2.
This is the value that we will go to use to compare to the value that being store in the variable name.
If one of the 2 cases returns true then the second line will be executed and print the statement if ever there are some statement to be display then break.
The use of the break here is to tell the program that this line will be the terminating line. Below is a sample code that can be use for us to know deeply how this switch statement works.
Sample Code<?php $my_var = “Monday”; switch($my_var) { Case “Monday”: echo “Today is Monday”; break; Case “Tuesday”: echo “Today is Tuesday”; break; Case “Wednesday”: echo “Today is Wednesday”; break; } ?>
If there is some question regarding with this article or need some help just CLICK HERE to be redirect to forum page.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button