Returning two values from a function

MacMac picture MacMac · Sep 28, 2010 · Viewed 87k times · Source

Is it possible to return two values when calling a function that would output the values?

For example, I have this:

<?php
    function ids($uid = 0, $sid = '')
    {
        $uid = 1;
        $sid = md5(time());

        return $uid;
        return $sid;
    }

    echo ids();
?>

Which will output 1. I want to chose what to ouput, e.g. ids($sid), but it will still output 1.

Is it even possible?

Answer

Gumbo picture Gumbo · Sep 28, 2010

You can only return one value. But you can use an array that itself contains the other two values:

return array($uid, $sid);

Then you access the values like:

$ids = ids();
echo $ids[0];  // uid
echo $ids[1];  // sid

You could also use an associative array:

return array('uid' => $uid, 'sid' => $sid);

And accessing it:

$ids = ids();
echo $ids['uid'];
echo $ids['sid'];