Do you need break in switch when return is used?

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?


Solution 1:

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.

Solution 2:

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

)

Solution 3:

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.

Solution 4:

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

Solution 5:

You don't need it, but I would strongly advise using it in any case as good practice.