Php switch case two conditions11/12/2023 ![]() You can also see this in the examples given above. When compared to if-else statements, it is more readable.Hence, the switch would work better while selecting from a large set of values. The number of comparisons made is lesser hence, reducing the compile time. As a result, instead of checking which case is satisfied throughout execution, it just decides which case must be completed. This is due to the creation of a jump table for switch during compilation. A switch statement is significantly faster than an if-else ladder if there are many nested if-else's involved. ![]() Some Key Advantages of Switch over If-Else Ladder After that, we go to case 11, encounter a print statement, and print 30. We go through the code till we find case 9. Let's consider the case when we want to find the number of days in the 9th month or September. So, instead of adding a print statement after each of these, we can have it only for one of them and add a break statement after that. We know that January, March, May, July, August, October, and December have 31 days, while April, June, September, and November have 30 days. In the above code, month 1 means January, month 2 means February, and so on. In switch, if we don't have a break statement, a matching case falls through until it encounters a break statement, which will be printed with the exception of the default case. The else statement can either be a single statement, or it can even be a block of statements. If it is true, control goes to one block of code, and if it isn’t, then control goes to a different block of code defined in else. The if-else statement allows the programmer to do exactly that with their code. If not a leap year February, the answer is 28. If the month is a leap year, February, the answer is 29. If the month is either April, June, September, and November, the answer is 30. If the month is either of January, March, May, July, August, October, and December, the answer is 31. For example, let's consider a situation where we need to think about the number of days present in each month. In our day-to-day lives, we always decide on things by using if-else. This is what we will cover in this article. It is hence important to understand the benefits and differences between each. While starting with coding,Īre one of the first things that you learn. Conditional Statements are if, else, else-if and switch. In coding, we use conditional statements for this purpose. For example, if you have already brushed your teeth, you can eat, else you will have to brush your teeth first. Sometimes your actions depend on your decisions. In our day-to-day lives, we make several decisions, from deciding what to wear to deciding what to eat.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |