views:

82

answers:

5

Is it possible for you 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?

+5  A: 

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'];
Gumbo
That would output `Array`
YouBook
@YouBook: You need to change the way you process the return value too.
Gumbo
Ah, my mistake, didn't read your edits. Anyway, great answer. :) *waits till I can accept this*
YouBook
@YouBook, check out `list` in my answer below. Very convenient feature.
webbiedave
+1  A: 
function ids($uid = 0, $sid = '') 
{ 
    $uid = 1; 
    $sid = md5(time()); 

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

$t = ids(); 
echo $t['uid'],'<br />';
echo $t['sid'],'<br />';
Mark Baker
+2  A: 

Return an array or an object if you need to return multiple values. For example:

function foo() {
    return array(3, 'joe');
}

$data = foo();
$id = $data[0];
$username = $data[1];

// or:
list($id, $username) = foo();
Adam Backstrom
+1 for hinting at objects as an alternative, adding semantical meaning. However, in time-critical situations, arrays might be a tiny bit faster (if in doubt, benchmark just to be sure).
Archimedix
A: 

You can use an array and the list function to get the info easily :

function multi($a,$b) {
   return array($a,$b);
}

list($first,$second) = multi(1,2);

I hope this will help you

Jerome

Jerome WAGNER
+1  A: 

Many possibilities:

// return array
function f() {
    return array($uid, $sid);
}
list($uid, $sid) = f();
$uid;
$sid;

// return object
function f() {
    $obj = new stdClass;
    $obj->uid = $uid;
    $obj->sid = $sid;
    return $obj;
}
$obj->uid;
$obj->sid;

// assign by reference
function f(&$uid, &$sid) {
    $uid = '...';
    $sid = '...';
}
f($uid, $sid);
$uid;
$sid;
nikic
I think better assign by reference... but this can be dangers!
Felipe Cardoso Martins