Multiple returns from a function

后端 未结 30 2276
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:12

Is it possible to have a function with two returns like this:

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}
<
相关标签:
30条回答
  • 2020-11-22 06:40

    I think eliego has explained the answer clearly. But if you want to return both values, put them into a array and return it.

    function test($testvar)
    {
      // do something
    
      return array('var1'=>$var1,'var2'=>$var2);
    //defining a key would be better some times   
    }
    

    //to access return values

    $returned_values = test($testvar);
    
    echo $returned_values['var1'];
    echo $returned_values['var2'];
    
    0 讨论(0)
  • 2020-11-22 06:42

    The answer that's given the green tick above is actually incorrect. You can return multiple values in PHP, if you return an array. See the following code for an example:

    <?php
    
    function small_numbers()
    {
        return array (0, 1, 2);
    }
    
    list ($zero, $one, $two) = small_numbers();
    

    This code is actually copied from the following page on PHP's website: http://php.net/manual/en/functions.returning-values.php I've also used the same sort of code many times myself, so can confirm that it's good and that it works.

    0 讨论(0)
  • 2020-11-22 06:43
    <?php
    function foo(){
      $you = 5;
      $me = 10;
      return $you;
      return $me;
    }
    
    echo foo();
    //output is just 5 alone so we cant get second one it only retuns first one so better go with array
    
    
    function goo(){
      $you = 5;
      $me = 10;
      return $you_and_me =  array($you,$me);
    }
    
    var_dump(goo()); // var_dump result is array(2) { [0]=> int(5) [1]=> int(10) } i think thats fine enough
    
    ?>
    
    0 讨论(0)
  • 2020-11-22 06:44

    You can return multiple arrays and scalars from a function

    function x()
    {
        $a=array("a","b","c");
        $b=array("e","f");
        return array('x',$a,$b);
    }
    
    list ($m,$n,$o)=x();
    
    echo $m."\n";
    print_r($n);
    print_r($o);
    
    0 讨论(0)
  • 2020-11-22 06:47

    I have implement like this for multiple return value PHP function. be nice with your code. thank you.

     <?php
        function multi_retun($aa)
        {
            return array(1,3,$aa);
        }
        list($one,$two,$three)=multi_retun(55);
        echo $one;
        echo $two;
        echo $three;
        ?>
    
    0 讨论(0)
  • 2020-11-22 06:48

    Yes, you can use an object :-)

    But the simplest way is to return an array:

    return array('value1', 'value2', 'value3', '...');
    
    0 讨论(0)
提交回复
热议问题