Is it possible to have a function with two returns like this:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
<
I think eliego has explained the answer clearly. But if you want to return both values, put them into a array and return it.
function test($testvar)
{
// do something
return array('var1'=>$var1,'var2'=>$var2);
//defining a key would be better some times
}
//to access return values
$returned_values = test($testvar);
echo $returned_values['var1'];
echo $returned_values['var2'];
The answer that's given the green tick above is actually incorrect. You can return multiple values in PHP, if you return an array. See the following code for an example:
<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
This code is actually copied from the following page on PHP's website: http://php.net/manual/en/functions.returning-values.php I've also used the same sort of code many times myself, so can confirm that it's good and that it works.
<?php
function foo(){
$you = 5;
$me = 10;
return $you;
return $me;
}
echo foo();
//output is just 5 alone so we cant get second one it only retuns first one so better go with array
function goo(){
$you = 5;
$me = 10;
return $you_and_me = array($you,$me);
}
var_dump(goo()); // var_dump result is array(2) { [0]=> int(5) [1]=> int(10) } i think thats fine enough
?>
You can return multiple arrays and scalars from a function
function x()
{
$a=array("a","b","c");
$b=array("e","f");
return array('x',$a,$b);
}
list ($m,$n,$o)=x();
echo $m."\n";
print_r($n);
print_r($o);
I have implement like this for multiple return value PHP function. be nice with your code. thank you.
<?php
function multi_retun($aa)
{
return array(1,3,$aa);
}
list($one,$two,$three)=multi_retun(55);
echo $one;
echo $two;
echo $three;
?>
Yes, you can use an object :-)
But the simplest way is to return an array:
return array('value1', 'value2', 'value3', '...');