ivytony Posted March 14, 2008 Share Posted March 14, 2008 I am wondering how to return multiple values from a function, array is a good way to go? Quote Link to comment https://forums.phpfreaks.com/topic/96175-how-to-return-multiple-values-from-a-function/ Share on other sites More sharing options...
BlueSkyIS Posted March 14, 2008 Share Posted March 14, 2008 yes. Quote Link to comment https://forums.phpfreaks.com/topic/96175-how-to-return-multiple-values-from-a-function/#findComment-492312 Share on other sites More sharing options...
accident Posted March 14, 2008 Share Posted March 14, 2008 yup function test(){ return array(1, 2, 3); } list($val1, $val2, $val3) = test(); Quote Link to comment https://forums.phpfreaks.com/topic/96175-how-to-return-multiple-values-from-a-function/#findComment-492313 Share on other sites More sharing options...
thebadbad Posted March 14, 2008 Share Posted March 14, 2008 Or you can just assign some global variables inside the function and don't return anything. <?php function test() { global $var1, $var2; list($var1, $var2) = array(1, 2); } test(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/96175-how-to-return-multiple-values-from-a-function/#findComment-492346 Share on other sites More sharing options...
laffin Posted March 14, 2008 Share Posted March 14, 2008 or assign a by reference function function swap(&$a,&$b) { $a~=$b; $b~=$a; $a~=$b; } $a1 = 15; $a2 = 75; swap($a1,$a2); echo "$a1,$a2"; Quote Link to comment https://forums.phpfreaks.com/topic/96175-how-to-return-multiple-values-from-a-function/#findComment-492402 Share on other sites More sharing options...
Psycho Posted March 14, 2008 Share Posted March 14, 2008 Or return an object: <?php function multiValues($number1, $number2) { $vals->average = ($number1+$number2)/2; $vals->max = ($number1>$number2)?$number1:$number2; $vals->min = ($number1<$number2)?$number1:$number2; return $vals; } $values = multiValues(5, ; echo $values->average; echo $values->max; echo $values->min; //Output: // 6.5 // 8 // 5 ?> Quote Link to comment https://forums.phpfreaks.com/topic/96175-how-to-return-multiple-values-from-a-function/#findComment-492426 Share on other sites More sharing options...
ivytony Posted March 14, 2008 Author Share Posted March 14, 2008 You guys are awesome! thank you! Quote Link to comment https://forums.phpfreaks.com/topic/96175-how-to-return-multiple-values-from-a-function/#findComment-492521 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.