Do you need break in switch when return is used?

You do not need a break, the return stops execution of the function.

(for reference: http://php.net/manual/en/function.return.php says:

If called from within a function, the return() statement immediately ends execution of the current function

)


No, you don't need a break in a switch case statement. The break is actually optional, but use with caution.


No its not necessary , because when the key word return is called it will indicate that the particular function which the switch/case was called has come to an end.


Yes, you can use return instead of break...

break is optional and is used to prevent "falling" through all the other case statements. So return can be used in a similar fashion, as return ends the function execution.

Also, if all of your case statements are like this:

case 'foo':
   $result = find_result(...);
   break;

And after the switch statement you just have return $result, using return find_result(...); in each case will make your code much more readable.

Lastly, don't forget to add the default case. If you think your code will never reach the default case then you could use the assert function, because you can never be sure.

Tags:

Php