SammyG SammyG - 1 month ago 5x
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;
{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


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.