00 Votes

PHP: Function with 2 or more return values

Question by Compi | 2017-05-16 at 20:05

Is PHP providing any possibility with which a function is able to return more than one single result value? For example, I have the following function:

function calcValues($x, $y) {
  return $x + $y;
}

As soon as the return line is reached, the whole function stops. With this, it is only possible to produce one return value. However, I need several ones. Is there any way to do that?

ReplyPositiveNegative
0Best Answer0 Votes

A function can return an array. With this, it is possible to transmit more than one return value at once because an array can have an arbitrary length.

Your function could look like that, for example:

function calcValues($x, $y) {
  $arr = array();
  $arr[0] = $x + $y;
  $arr[1] = $x * $y;
  return $arr;
}

You will get the same result with:

function calcValues($x, $y) {
  $arr = array($x + $y, $x * $y);
  return $arr;
}

And you can call the function in the following way:

$arr = calcValues(2, 3);
echo $arr[0]; // 5
echo $arr[1]; // 6

As you can see, we pass two numbers to this function here. The function returns an array in which the sum as well as the product of the two figures are stored. Within the function, the array is created and after calling the function, we can read out and output the single elements of the array.
2017-05-16 at 22:08

ReplyPositive Negative
Reply

Related Topics

PHP: Upload of large Files

Tutorial | 0 Comments

PHP: Current Date and Time

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.