SammyG SammyG - 3 months ago 9
PHP Question

Return 2 things from a function

I have a function that returns a multidimensional array, but I also need to return a single value. I am currently using the single value via the global keyword, so I can modify it inside the function.

But I'm wondering if there is another/better way to return 2 values from a function?

Current (pseudo) code:

global $iNumber;
$arrResult;
{do some calculations and queries}

$iNumber = 73;
return $arrResult;


The function that called this function can use the array of arrays, and also the global variable which has been updated to 73.

But is there another/better way to combine or pass these two different values?

Answer

You can do it in two ways: to return an array or an object.

Array solution:

function calculate(...) {
   //do some stuff
   return ['result' => $arrResult, 'iNumber' => $iNumber];
}

Object solution:

function calculate(...) {
   //do some stuff
   $object = new stdClass();
   $object->result = $arrResult;
   $object->iNumber = $iNumber;
   return $object;
}

stdClass is just an example and you can create your own class for this purpose.