I was wondering if I need to use break in a switch function when return is used.
function test($string)
{
switch($string)
{
case 'test1':
return 'Test 1: ' . $string;
case 'test2':
return 'Test 2: ' . $string;
}
}
I’ve tried it, and it works just fine without break. But is this safe?
Yes, you can use
returninstead ofbreak…breakis optional and is used to prevent “falling” through all the othercasestatements. Soreturncan be used in a similar fashion, asreturnends the function execution.Also, if all of your
casestatements are like this:And after the
switchstatement you just havereturn $result, usingreturn find_result(...);in eachcasewill make your code much more readable.Lastly, don’t forget to add the
defaultcase. If you think your code will never reach thedefaultcase then you could use theassertfunction, because you can never be sure.