ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

PHP Code Example on Switch Statement:Making Choice and Cases

Updated on August 3, 2012

PHP example, php code example on switch statement.

How do switch statement works in PHP programming? This hub will contain a php example code on switch statement and sample output.

Note: The php file name switchstatement.php is connected to the html file named switchstatement.html that will be given below. If you do not know how to run html file on your browser, see this:

HTML Basic: How to Run HTML File on your Browser.

And also, if you do not know how to run a php file please check the link below for details:

How to run PHP Code on your Browser with XAAMP and Notepad++.

Now, let's begin!

switchstatement.html Sample Code

<html>
<body>
	<center><h1>Switch Statement</h1></center><br />
	<p><strong>What Do You Want To Learn More? Choose Below:</strong></p>
	<p>1. Java</p>
	<p>2. PHP</p>
	<p>3. C++</p>
	<p>4. Ruby</p>
	
	<form method = "post" action = "switchstatement.php">
	<table>
	<tr>
		<td><strong>Enter the Number of your choice: <strong></td>
		<td><input type = "text" name = "choice"> </td>
	</tr>
	<tr>
		<td></td>
		<td><input type = "submit" name = "submit" value="SUBMIT"> </td>
	</tr>
	</table>
	
</body>
</html>

swtichstatement.html Sample Output

PHP Code Example on switchstatement.php

<?php
	$choice = $_POST['choice'];
	
	if($_POST['submit'])
	{
		switch($choice)
		{
			case 1:
				echo "Oh, That's Good! You Love Java!";
				break;
			case 2:
				echo "Oh, That's Good! You Love PHP!";
				break;
			case 3:
				echo "Oh, That's Good! You Love C++!";
				break;
			case 4:
				echo "Oh, That's Good! You Love Ruby!";
				break;
			default:
				echo "You Did Not Enter A Number For Choices!";
				
		}
	}
?>

switchstatement.php Sample Output

Beginner's Guide on Testing the Codes

For the sake of clarification, here is a step by step guide to be able to run and test the code successfully.

1. Install Xaamp and Notepad++ in your computer

2. Open the Xaamp interface and run Mysql as well as Apache

3. Open notepad++ and copy the switchstatement.html, save it on the drive where you installed your Xaamp and open the xammp folder, then open the htdocs folder and save the html file with the same name I have given.

4. Copy and paste also the switchstatement.php and follow the step above.

5. Now go to your browser and type this: localhost/switchstatement.html

By doing so, you could be able to test how the codes work.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      creativeroy 4 years ago

      Good example on PHP Switch Statement.

    • aisha91 profile image
      Author

      Rasna Aisha 4 years ago from Manila, Philippines

      Thank you, creativeroy, for stopping by :)

    Click to Rate This Article