I was wondering if I need to use \"break\" in \"switch\" function when \"return\" is used.
function test($string)
{
switch($string)
{
case \'test1\':
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
)
Break is just a cautionary statement used to limit the control of switch stucture from going into another case...for example if you have three case statements and value is for first case and you have used case without any break structure then all the following cases will be executed inspite of the condition being satisfied only for the first case... Return can perform the asme function so it won't be a problem if you use return in place of break because return will take control away from the switch case statement which is the need at that moment...... hope it helps....
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.
No, you don't need a break
in a switch case
statement. The break
is actually optional, but use with caution.
You don't need it, but I would strongly advise using it in any case as good practice.
return gives the control back to the calling method, where as break jumps to the first instruction after the switch block.