1

Is it possible to return multiple items from a function - and assign them to several variables in a single statement - like can be done in some languages (e.g. Python) ?

For example, can I have something like this:

a, b, c,d = foo();
oompahloompah
  • 9,087
  • 19
  • 62
  • 90

3 Answers3

8

A function can not return multiple values, but similar results can be obtained by returning an array.

<?php
function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

See http://php.net/manual/en/functions.returning-values.php

tofutim
  • 22,664
  • 20
  • 87
  • 148
1

Tou can do it if you`ll return an array in function and then use list construction:

function foo(){
    ...
    return array('a', 'b', 'c');
}

list($a, $b, $c) = foo();
Hck
  • 9,087
  • 2
  • 30
  • 25
1

Yes it is possible. You can return an array from the function and use the using the list construct to assign the array elements to variables in one statement:

function fun() {
        return array(1,2,3);
}

// this will assign 1 to $a, 2 to $b and 3 to $c.
list($a,$b,$c) = fun();

See it

codaddict
  • 445,704
  • 82
  • 492
  • 529