-5

I am creating a simple web site in PHP, and I want to return multiple variables from one function. Is that possible or not?

And if possible, then how?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mayank Vadiya
  • 1,437
  • 2
  • 19
  • 32
  • Please read this http://stackoverflow.com/help/how-to-ask your question is incomplete. Anything is possible! – Pogrindis Jul 08 '15 at 13:15
  • than say how it possible? – Mayank Vadiya Jul 08 '15 at 13:18
  • There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.I would suggest that you find a development forum (perhaps [quora](http://www.quora.com/Computer-Programming)?) to work out generalities. Then, when/if you have specific coding issues, come back to StackOverflow and we'll be glad to help. – Jay Blanchard Jul 08 '15 at 13:21
  • Define an object which semantically encapsulates those values into a meaningful structure. Return an instance of that object. – David Jul 08 '15 at 13:23
  • It is also a duplicate of *[Multiple returns from a function](https://stackoverflow.com/questions/3451906)* (though that question is ambiguous). – Peter Mortensen Dec 12 '19 at 21:51

4 Answers4

2

Put them into an array:

function myFunction() {
    return array('name' => 'Joe', 'birthday' => '1976. 08. 29');
}

So after this, you can say:

$data = myFunction();
echo $data['name'] . "\n";
echo $data['birthday'];

If your array is not fixed, then you can loop through all of the keys and items:

foreach ($data as $key => $value) {
   echo $key . ": " . $value . "\n";
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vaso123
  • 12,347
  • 4
  • 34
  • 64
1

You can return an array,

function doSth(){
    $a = 2;
    $b = 5
    $c = 9;
    return array($a, $b, $c);
}

and then use the list() method to get back single values:

list($a, $b, $c) = doSth();
echo $a; echo $b; echo $c;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dognose
  • 20,360
  • 9
  • 61
  • 107
0

You can do this using arrays and the list() function:

function doSomething(){
  // do stuff
  return [$a, $b];
}

list($a, $b) = doSomething();
M1ke
  • 6,166
  • 4
  • 32
  • 50
-1
< ?php

function multiple_returns()
{
    return array( 1, 2, "three" );
}

?>
Ravi Chauhan
  • 1,409
  • 13
  • 26