O
O
Optimus2015-10-31 00:06:47
PHP
Optimus, 2015-10-31 00:06:47

Can a function return 2 values?

$a = 2; $b = 3;
function Num($a, $b){
   $c = $a + $b;
   $d = $a * $b;
   return $c, $d; // Вот тут весь вопрос
}

Question: Can I use return to return not one but two values ​​without tambourines like implode or combining them into an array, etc.?
Or do I need to write 2 functions here according to my mind - one will return the value of addition and the second of multiplication?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2015-10-31
Pyan @marrk2

You can return an array

$a = 2; $b = 3;
function Num($a, $b){
   $c = $a + $b;
   $d = $a * $b;
   return [$c, $d];
}
list($c, $d) = Num($a, $b);
echo "$c|$d";
// 5|6

You can change a variable through a pointer
$a = 2; $b = 3; $c = $d = null;
function Num($a, $b, &$c, &$d){
   $c = $a + $b;
   $d = $a * $b;
}

Num($a, $b, &$c, &$d);
echo "$c|$d";
// 5|6

And if you write
return $c;
return $d;

then only the first one will work. after return, the function returns a value and execution does not go any further.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question