How to Create Function With Multiple Returns in PHP


If you need to create a PHP function that returns multiple values, then you can do one of the following.

Option 1 – Returning an array

function returnArray() {
  return array("one", "two");
}

// call the function and print the response
var_dump(returnArray());

Option 2 – Returning a conditional

function returnConditional($x = true) {
  if ($x) return "one";
  else return "two";
}

// call the function with a value and print the response
var_dump(returnConditional(false));

Option 3 – Using generator to yield values

function multipleValues() {
  yield "one";
  yield "two";
}

$res = multipleValues();
foreach($res as $r) {
  echo $r; // first val=="one", second val=="two"
}