Page 1 of 1
return'ing 2 values
Posted: Tue May 17, 2005 12:25 pm
by malcolmboston
ok, standard return
Code: Select all
// function definition
function add1 ($value)
{
$value = ($value + 1);
return $value;
}
// call and retrieval
$value = 26;
$number = add1 ($value)
what if i wanted to do...
Code: Select all
function add1 ($value)
{
$value = ($value + 1);
$multiply = ($value * 5);
return $value;
return $multiply;
}
how would i write my code for actually returning it, eg (complete pseudo code).
can it be done without seperate function calls?
Posted: Tue May 17, 2005 12:32 pm
by Roja
Cheesy, but accomplishes the request:
Code: Select all
function add1 ($value)
{
$value = ($value + 1);
$multiply = ($value * 5);
$returnї1] = $value;
$returnї2] = $multiply;
return $return;
}
$return = add1($value);
$value = $returnї1];
$multiply = $returnї2];
Posted: Tue May 17, 2005 1:08 pm
by Burrito
yup, I think that's the only way to do it...as soon as the function hits return, it's all over and it dies a horrible death.
putting everything you want into an array and returning the array is the only way to go...
Posted: Tue May 17, 2005 1:47 pm
by Roja
Burrito wrote:yup, I think that's the only way to do it...as soon as the function hits return, it's all over and it dies a horrible death.
putting everything you want into an array and returning the array is the only way to go...
Actually, I can think of other ways to do it.. although each is more horrible than the first:
Code: Select all
function add1 ($value)
{
global $value, $multiply;
$value = ($value + 1);
$multiply = ($value * 5);
}
add1($value);
(Evil for the use of global-scope variables)
There are others, but I suspect the fill-an-array, return-the-array approach is the 'cleanest' architecturally. I'd be interested in hearing better ways.
Posted: Tue May 17, 2005 1:59 pm
by Chris Corbyn
I would too but from a function alone it seems like common sense to just use an array.
I have never really thought of trying any other way...
Posted: Tue May 17, 2005 5:19 pm
by andre_c
another way... pass parmameters as references, but that does get uglier
Posted: Tue May 17, 2005 5:34 pm
by Todd_Z
Code: Select all
function doSomething ( $val ) {
$vals = array();
$vals[] = $val % 5;
$vals[] = $val % 6;
return $vals;
}
list( $ret1, $ret2 ) = doSomething( 929 );
echo "Return value #1: $ret1\t\t Return value #2: $ret2";