This forum is now read-only. Please use our new forums at

Control Flow: Switch Forum

View Course » View Exercise

1234 points
Submitted by
about 5 years ago

why "true" into switch?

I kind of get the whole thing but i dont' get why

switch (true)

contain "true", it's probably something really really stupid i guess but please help :)

Thanks in advice for any help

1 vote


I guess you're speaking of the "Advanced Switch". The reason why you set it to true: A switch statement is just a if statement. The whole thing would be the same as doing the following:
if (!preg_match('([a-zA-Z].*[0-9]|[0-9].*[a-zA-Z])) { $isValid = false; } and
if (strlen($i) > 30)) { $isValid = false; } But: We can make it inside a switch as shown in the exercise. As, if the "case" returns true, which means it's invalid, it sets the variable and breaks it. Otherwise if it's false it ignores it, and continues to the next check. If all checks return false: The username is valid and the default case hits in. You could remove the default case and later instead of if ($isvalid == false) { echo 'Invalid username'; } (You would later check with this was the username valid, forgot to mention it on the exercise). So, if you would remove the default case, you could check if it's valid by if (isset($isvalid)) { echo 'Invalid username'; }. If that didn't shed any light on the exercise, I'm willing to go deeper into this.

Adding this: You could also do switch (false) and replace the ! from the preg_match and instead of doing strlen > 30' you would dostrlen < 30`. The result would be the same. You're just checking if the IF statement inside the CASE returns true or false.

504 points
Submitted by
about 5 years ago

0 votes


I wouldn't look too closely at this construct as it's a bad idea on pretty much every level. switch(true) is more verbose than if/else if/else for no good reason. Putting a regex in a beginner's first programming tutorial is an awful idea. Making the cases double negatives ("if not condition then $isvalid is false") is unnecessarily confusing.

I asked some professional programmers I know if "switch(true)" is as bad an idea as I think it is. To a man, the responses were "Wait, what? And yes."

1990 points
Submitted by
Chad Miller
about 5 years ago

1 Comment

2b153953ef015ea1708bd5f306bd2bb6?s=140&d=retro Roni about 5 years ago

Actually, from my knowledge, there's nothing bad using "switch (true)", considering for example Zend, Symfony and Laravel uses it in some occasions. It probably isn't the best in this example. I did consider leaving out the exercise because of the RegEx, but I decided to leave it. I'll consider removing it, or making it more simple.