Decision Making Using PHP Switch Statement
Decision Making Using PHP Switch StatementHi, Here is a good shepherd with his sheep again. Today I am going to discuss Switch Statement. The basic concept of Switch is similar to the IF-ELSE statement; it helps you to write decision making code just like IF-ELSE but it is a little more organized, elegant and handy when dealing with complex logics as compare to IF-ELSE. Remember, you can convert every IF-ELSE programme to Switch syntax but vice versa is not possible in some situations. Remember one more thing, it is not necessary to convert IF-ELSE to Switch and vice versa, just use whatever suits to your needs, though when handling the complex and large decision making code I would suggest to use Switch. Let’s have a look at its syntax. Switch Statement Syntax:switch (input) Explanation:The parenthesis of Switch accepts a value which is matched with cases and if any case if found true the block of code for that case is executed. If the input doesn’t match with any of the cases then the code block under ‘default’ is executed. every case is headed by keyword ‘case’ following by its value and a colon (:). Every case ends with a break statement. What is break statement: break statement breaks the flow of a certain code block in which it resides and take the control out of the block. You can use break without switch statement too for example to take the control out from a FOR loop (will discuss later) or IF statement. Let’s write a simple programme to understand the use of Switch statement in PHP. <?php Here we have hard-coded $site value so the first case will stand true and the programme will display www.fastcreators.com and the break statement of case will take out the control from Switch body. ‘Default’ does not require any break statement as it is the last option of the switch statement. Switch statement’s body starts and closes with braces. Assignment:Make a form that has different countries names in a drop-down list. After you select a country and submit the form the accepting page should use Switch statement to check the country name and then display its Capital, Currency Name and National Language. You can post your assignments on haroon[at]fastcreators[dot]com. Till we gather on another article take good care of yourself and keep practicing. - Haroon Ahmad Series: Fast PHP Articles
|






Recent comments
45 min 5 sec ago
1 hour 38 min ago
3 hours 59 min ago
4 hours 16 min ago
4 hours 48 min ago
6 hours 3 min ago
6 hours 45 min ago
7 hours 13 min ago
14 hours 40 min ago
18 hours 10 min ago