SammyG SammyG - 3 months ago 18
PHP Question

Returning an Array AND a single value

I have a function that returns an array of arrays; but I also need to return a single value. I am currently using the single value as a global variable; but I'm wondering if there is another/better way?

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?

Thank you

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.