How to Create Function with Multiple Returns in PHP

0 min read 104 words

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"
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags