Do you need break in switch when return is used?

后端 未结 8 1786
温柔的废话
温柔的废话 2021-01-30 18:56

I was wondering if I need to use \"break\" in \"switch\" function when \"return\" is used.

function test($string)
{
  switch($string)
  {
    case \'test1\':
            


        
相关标签:
8条回答
  • 2021-01-30 19:46

    Starting with PHP 8 (Nov 2020), you can use match:

    <?php
    
    function test($string) {
       return match ($string) {
          'test1' => 'Test 1: ',
          'test2' => 'Test 2: '
       } . $string;
    }
    

    Although in this case you could just use an array:

    <?php
    
    function test($string) {
       return [
          'test1' => 'Test 1: ',
          'test2' => 'Test 2: '
       ][$string] . $string;
    }
    

    https://php.net/control-structures.match

    0 讨论(0)
  • 2021-01-30 20:02

    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.

    0 讨论(0)
提交回复
热议问题