Using For and Switch in place of a bunch of if statements. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Using For and Switch in place of a bunch of if statements.

Ex 1: if (condition) { if (condition) { if (condition) { Some code... } } } Ex 2: For ($i = 0; $i <= 3; $i++) { switch ($i) { case 1: if (condition) { Some code... } else { $i = 4; } break; case 2: if (condition) { Some code... } else { $i = 4; } break; case 3: if (condition) { Some code... } else { $i = 4; } break; } } My question is if example 2 is acceptable to use because I feel like when you have more than like 5 if statements than example 2 would probably be easier to manage.

6th Feb 2019, 1:51 PM
Colin
Colin - avatar
1 Answer
+ 2
The 1st example is not the same as the 2nd. It's a nested conditional. The equivalent of the switch statement is something like this: if (condition) {...} else if (condition) {...} else if (condition) {...} ... else {...} switch is a good choice even if you have two or more if conditions
30th Mar 2019, 9:40 AM
Pete Wright
Pete Wright - avatar