Is it possible to have a function with 2 returns like this:
function test($testvar)
{
// do something
return $var1;
return $var2;
}
If so, how would I be able to get each return separately?
Is it possible to have a function with 2 returns like this:
function test($testvar)
{
// do something
return $var1;
return $var2;
}
If so, how would I be able to get each return separately?
In your example, the second return will never happen - the first return is the last thing PHP will run. If you need to return multiple values, return an array:
function test($testvar) {
return array($var1, $var2);
}
$result = test($testvar);
echo $result[0]; // $var1
echo $result[1]; // $var2
The answer is no. When the parser reaches the first return statement, it will direct control back to the calling function - your second return statement will never be executed.
What you're looking for is a continuation style returns and it's not really supported in PHP (it is supported in functional languages like scheme). The closet thing you can do is store a global state variable when the function is called the first time increment the global, then have a condition that checks the variables state on the second call.
global var $tester = 0;
function test($testvar) {
if($tester===0) {
$tester++;
return $var1;
} else {
return $var2;
}
}
There is no way of returning 2 variables. Although you CAN propagate an array an return it; create a conditional to return a dynamic variable, etc.
For instance, This function would return $var2;
function wtf($blahblah = true) {
$var1 = "ONe";
$var2 = "tWo";
if($blahblah == true) return $var2;
return $var1;
}
In application:
echo wtf();
//would echo: tWo
echo wtf("not true, this is false");
//would echo: ONe
If you wanted them both, you could modify the function a bit
function wtf($blahblah = true) {
$var1 = "ONe";
$var2 = "tWo";
if($blahblah == true) return $var2;
if($blahblah == "both") {
$anArray[] = $var1;
$anArray[] = $var2;
return $anArray;
}
return $var1;
}
echo wtf("both")[0]
//would echo: ONe
echo wtf("both")[1]
//would echo: tWo
Languages which allow multiple returns usually just convert the multiple values into a data structure.
For example, in python you can return multiple values, however they're actually just being returned as 1 tuple.
So you can return multiple values in PHP by just creating a simple array and returning that.
Hi
You can get values of two or more variables by setting them by reference
function t(&$a, &$b) {
$a = 1;
$b = 2;
}
t($a,$b);
echo $a . ' ' . $b;
output:
1 2