Home  >  Q&A  >  body text

function returns multiple times

Is it possible to have a function with two return values ​​like this:

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

If so, how can I get each return separately?

P粉022285768P粉022285768231 days ago479

reply all(2)I'll reply

  • P粉548512637

    P粉5485126372024-03-26 11:41:34

    Technically, you cannot return multiple values. However, there are ways to work around this limitation. The most similar way to return multiple values ​​is to use the list keyword:

    function getXYZ()
    {
        return array(4,5,6);
    }
    
    list($x,$y,$z) = getXYZ();
    
    // Afterwards: $x == 4 && $y == 5 && $z == 6
    // (This will hold for all samples unless otherwise noted)

    Technically, you return an array and use list to store the elements of that array in different values, rather than storing the actual array. Using this technique will make it feelmost like returning multiple values.

    list The solution is a php specific one. Some languages ​​have similar structures, but many more don't. There is another method that is commonly used to "return" multiple values, and is available in almost every language (in one way or another). However, this approach looks completely different, so it may take some getting used to.

    // note that I named the arguments $a, $b and $c to show that
    // they don't need to be named $x, $y and $z
    function getXYZ(&$a, &$b, &$c)
    {
        $a = 4;
        $b = 5;
        $c = 6; 
    }
    
    getXYZ($x, $y, $z);

    This technology is also used in some functions defined by PHP itself (for example, # in str_replace, $matches in preg_match). This might feel a lot different than returning multiple values, but it's at least worth knowing about.

    The third method is to use an object to hold the different values ​​you need. This requires more input, so it's used less frequently than the two methods above. Still, it might make sense to use this feature when the same set of variables is used in multiple places (or, of course, in a language that doesn't support the above method or allows you to do it without additional typing).

    class MyXYZ
    {
        public $x;
        public $y;
        public $z;
    }
    
    function getXYZ()
    {
        $out = new MyXYZ();
        
        $out->x = 4;
        $out->y = 5;
        $out->z = 6;
        
        return $out;
    }
    
    $xyz = getXYZ();
    
    $x = $xyz->x;
    $y = $xyz->y;
    $z = $xyz->z;

    The above method summarizes the main ways for functions to return multiple values. However, there are some variations on these methods. The most interesting variants are those that actually return an array, since you can do a lot with arrays in PHP.

    First, we can simply return an array without treating it as anything other than an array:

    function getXYZ()
    {
        return array(1,2,3);
    }
    
    $array = getXYZ();
    
    $x = $array[0];
    $y = $array[1];
    $z = $array[2];

    The most interesting part of the code above is that the code inside the function is the same as in the first example I provided; only the code that calls the function has changed. This means that what the caller of the function does with the results returned by the function is up to the person who called the function.

    Alternatively, you can use an associative array:

    function getXYZ()
    {
        return array('x' => 4,
                     'y' => 5,
                     'z' => 6);
    }
    
    $array = getXYZ();
    
    $x = $array['x'];
    $y = $array['y'];
    $z = $array['z'];

    Php does have the

    compact function which allows you to do the same thing as above but write less code. (Well, the example won't have less code, but the real-world application probably will.) However, I think the typing savings are minimal, and it makes the code harder to read, so I wouldn't do it myself. However, here is an example:

    function getXYZ()
    {
        $x = 4;
        $y = 5;
        $z = 6;
        
        return compact('x', 'y', 'z');
    }
    
    $array = getXYZ();
    
    $x = $array['x'];
    $y = $array['y'];
    $z = $array['z'];

    It should be noted that while

    compact does have a counterpart in extract that can be used in the calling code here, since using it is a bad idea ( Especially for something as simple as this), I won't even give a sample of it. The problem is, it "magically" creates the variables for you, and you can't see what variables are created without looking in other parts of the code.

    Finally, I would like to mention that list does not work well with associative arrays. The following will meet your expectations:

    function getXYZ()
    {
        return array('x' => 4,
                     'y' => 5,
                     'z' => 6);
    }
    
    $array = getXYZ();
    
    list($x, $y, $z) = getXYZ();

    However, the following will do something different:

    function getXYZ()
    {
        return array('x' => 4,
                     'z' => 6,
                     'y' => 5);
    }
    
    $array = getXYZ();
    
    list($x, $y, $z) = getXYZ();
    
    // Pay attention: $y == 6 && $z == 5

    If you use list with an associative array, and someone else has to change the code in the called function in the future (which can happen in any case), it may break suddenly, so I recommend Do not use list arrays with associative arrays.

    reply
    0
  • P粉717595985

    P粉7175959852024-03-26 09:06:04

    Cannot return 2 variables. However, you can propagate an array and return it; create conditions to return dynamic variables, etc.

    For example, this function will return $var2

    function wtf($blahblah = true) {
        $var1 = "ONe";
        $var2 = "tWo";
    
        if($blahblah === true) {
          return $var2;
        }
        return $var1;
    }

    In app:

    echo wtf();
    //would echo: tWo
    echo wtf("not true, this is false");
    //would echo: ONe

    If you want both, you can slightly modify the function

    function wtf($blahblah = true) {
        $var1 = "ONe";
        $var2 = "tWo";
    
        if($blahblah === true) {
          return $var2;
        }
    
        if($blahblah == "both") {
          return array($var1, $var2);
        }
    
        return $var1;
    }
    
    echo wtf("both")[0]
    //would echo: ONe
    echo wtf("both")[1]
    //would echo: tWo
    
    list($first, $second) = wtf("both")
    // value of $first would be $var1, value of $second would be $var2

    reply
    0
  • Cancelreply