If we have the "switch" statment, the "else if" statment is not needed anymore! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

If we have the "switch" statment, the "else if" statment is not needed anymore!

Why we need the other statment?

27th Jun 2016, 7:23 PM
Ivan
Ivan - avatar
3 Answers
+ 2
I think so
27th Jun 2016, 9:21 PM
Martin
Martin - avatar
+ 2
actually I think its more like the other way around. The "switch" statement allows you to develope sequense of conditions in a linear way. That means you can only check one varieable at a time and have to define for each specific case what will happen. This linear manner of conditioning can prove to be very limited. Because once a cirtain case would meet its condition, the "break" statement would apply and the entire procccess would eliminate. You would have to write an entire new "switch" statment to go over the process again or to recive a different output. the "else if" statement on the other hand creates a binary conditional system. That means each condition can give 2 different outcomes (condition is met / condition is not met) and each one of the 2 states could have 2 different conditions of its own, and so does their 2 states, and so on. Furthur more, the binary conditions tree may be as complex as you wish, creating the same outcome if a certain number of conditions isin't met (for example: unchecked fields of entery), or different outcomes for each specific condition. At the latter case you might really want to use a "Switch" statement, but the point is the switch statement is only capeable of that linear, different output for each individual condition, while the "else if" has a much wider variety of possible applications. At least that is how I came to think about it 😶
29th Jun 2016, 9:57 AM
Rotem
+ 2
Not if else if statements can be represented using switch example if (a% 2==0) echo "abc"; else if (a% 3==1) echo "def"; else if (a% 5==3) echo "ifg"; else if (a% 7==1) echo "djd" cannot be represented by switch
1st Jul 2016, 6:19 PM
Midhun Mathew