In this tutorial we will show you the solution of switch case in PHP with user input, as we know that switch statement is used where we have multiple conditions.
In one line, it is the advanced version of if else statement. We don’t need to use else again and again many times, we only have to use cases inside switch only with break.
Today, in this article we will see how to use this switch statement with user input in php. Let’s see.
Step By Step Guide On Switch Case In PHP With User Input :-
Here, first of all we have to create a form with input field and a submit button.
After inputting the value and click on submit button the switch statement checks the cases with conditions and execute the required block of codes.
Here, below we are going to show you an example. Let us understand this first.
<form action=" " method="post"> <label> Enter a number between 1 - 26 </label> <input type="text" name="number"> <input type="submit" name="submit"> </form> <?php // if the form has been submitted if(isset($_POST['submit'])) { $number = (int) $_POST['number']; switch($number) { case 1: echo "A"; break; case 2: echo "B"; break; case 3: echo "C"; break; case 4: echo "D"; break; case 5: echo "E"; break; case 6: echo "F"; break; case 7: echo "G"; break; case 8: echo "H"; break; case 9: echo "I"; break; case 10: echo "J"; break; case 11: echo "K"; break; case 12: echo "L"; break; case 13: echo "M"; break; case 14: echo "N"; break; case 15: echo "O"; break; case 16: echo "P"; break; case 17: echo "Q"; break; case 18: echo "R"; break; case 19: echo "S"; break; case 20: echo "T"; break; case 21: echo "U"; break; case 22: echo "V"; break; case 23: echo "W"; break; case 24: echo "X"; break; case 25: echo "Y"; break; case 26: echo "Z"; break; default: echo 'wrong number'; } } ?>
- Here, as we can said that we create a form with type post and then inside this form we create an input with type text and a submit button to submit that number.
- After this we will create a basic structure of php in which <?php is our starting tag and ?> is our ending tag. Inside these tags we will write of php codes.
- Now, here we use isset on form submit button and then get the value that user filled inside the input tag inside a variable. You can also see the above example to understand how to done that.
- Now, at next step we just use our switch statement and cases inside this switch to execute the required output.
- In this article, we use example of A to Z with number from 1 to 26.
Conclusion :-
At last in conclusion, here we can say that with the help of this article we are able to understand how to use switch case in php with user input.
I hope this tutorial on helps you and the steps and method mentioned above are easy to follow and implement.