Is using the break statement bad practice?

How do I write this same code to do the same thing but without using a switch statement?

  • $month=date("F"); print($month); print("<br>"); switch ($month){ case "January": $bgcolor = red; break; case "February": $bgcolor = orange; break; case "March": $bgcolor = green; break; case "April": $bgcolor = blue; break; case "May": $bgcolor = green; break; default: $bgcolor = pink; } //end switch How would this code output the same change the background color of a webpage but without using the switch statement?

  • Answer:

    If statements. It's rather less elegant and readable than switch but it will work. As in; If ($month== January) { $bgcolor = red }; If blabla bla

jr at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

You could do this if you had to use something other than a switch if ( $month == 'January' ) $bgcolor = 'red'; elseif ( $month == 'February' ) $bgcolor = 'orange'; elseif ( $month == 'March' ) $bgcolor = 'green'; elseif ( $month == 'April' ) $bgcolor = 'orange'; elseif ( $month == 'May' ) $bgcolor = 'green'; else $bgcolor = 'pink';

A switch statement is just a cleaner way of doing: if ... elseif ... else $month=date("F"); print($month); print("<br>"); if ($month == 'January') {$bgcolor = red;} else if ($month == 'February') {$bgcolor=orange;} ... ... else {$bgcolor=pink;} I don't see why you'd do that though.

simple use if and else statement

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.