I have a function that should return several values. Is this possible, perhaps with an array? If so, how would I reference that array? Do I have any alternatives to using an array?

share|improve this question

possible duplicate of multiple returns from function – Daniel Vandersluis Aug 26 '10 at 22:08
feedback

8 Answers

up vote 33 down vote accepted

There are multiple ways. Arrays are indeed a possibility, consider the following:

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

list($x,$y,$z) = getXYZ();

This is a rather php-specific solution. Another way is using pass by reference, which is actually available in a number of other languages as well:

function getXYZ(&$x1. &$y1, &$z1)
{
    $x = 1;
    $y = 2;
    $z = 3; 
}

getXYZ($x, $y, $z);

Alternatively, you can also wrap the different values in a class, but as it's some more typing and inconvenience, the two ways above are used more often. In other languages I have seen this approach used, though mainly when the same set of details (which were related) were necessary in a number of instances (or in languages where it wouldn't take more typing).

share|improve this answer
1  
Also: return compact('var1', 'var2', 'var3'); – handsofaten Aug 26 '10 at 22:37
That is another option, but it is doesn't feel to me as returning multiple values, just as returning an array. That may just be me though. Personally, I would find return array('x' => $x, 'y' => $y, 'z' => $z) cleaner, but to the point where I would write it myself, not to the point where I would ask others to use that format. – Jasper Aug 26 '10 at 22:54
Using List() is a great answer to a simular problem I had. this is an excellent way validate and return multiple variables back into a function. a quick look at the php docs will shed more light on this function and perhaps make it more clear. php.net/manual/en/function.list.php .. thanks Jasper! – Justin Pfister Oct 19 at 20:22
feedback

Functions, by definition, only return one value.

However, as you assumed, that value can be an array.

So you can certainly do something like:

<?PHP
function myfunc($a,$b){
   return array('foo'=>$a,'bar'=>$b);
}
print_r(myfunc('baz','bork'));

That said, it's worth taking a moment and thinking about whatever you're trying to solve. While returning a complex result value (like an array, or an object) is perfectly valid, if you're thinking is that "I want to return two values", you might be designing poorly. Without more detail in your question, it's hard to say, but it never hurts to stop and think twice.

share|improve this answer
feedback

Or you can pass by reference:

function byRef($x, &$a, &$b)
{
    $a = 10 * $x;
    $b = 100 * $x;
}

$a = 0;
$b = 0;

byRef(10, $a, $b);

echo $a . "\n";
echo $b;

This would output

100
1000
share|improve this answer
feedback

yes, you can use an object :-)

but the simplest way is to return an array:

return array('value1','value2','value3','...');
share|improve this answer
feedback

yes and no, you can't return more than one variable / object, but as you suggest, you can put them into an array and return that, there is no limit to the nesting of arrays so you can just package them up that way to return

share|improve this answer
feedback

Functions in PHP can return only one variable. you could use variables with global scope, you can return array, or you can pass variable by reference to the function and than change value,.. but all of that will decrease readability of your code. I would suggest that you look into the classes.

share|improve this answer
feedback

Thought I would expand on a few of the responses from above....

class nameCheck{

public $name;

public function __construct(){
    $this->name = $name;
}

function firstName(){
            // If a name has been entered..
    if(!empty($this->name)){
        $name = $this->name;
        $errflag = false;
                    // Return a array with both the name and errflag
        return array($name, $errflag);
            // If its empty..
    }else if(empty($this->name)){
        $errmsg = 'Please enter a name.';
        $errflag = true;
                    // Return both the Error message and Flag
        return array($errmsg, $errflag);
    }
}

}


if($_POST['submit']){

$a = new nameCheck;
$a->name = $_POST['name'];
//  Assign a list of variables from the firstName function
list($name, $err) = $a->firstName();

// Display the values..
echo 'Name: ' . $name;
echo 'Errflag: ' . $err;
}

?>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" >
<input name="name"  />
<input type="submit" name="submit" value="submit" />
</form>

This will give you a input field and a submit button once submitted, if the name input field is empty it will return the error flag and a message. If the name field has a value it will return the value/name and a error flag of 0 for false = no errors. Hope this helps!

share|improve this answer
feedback

You can always only return one variable which might be an array. But You can change global variables from inside the function. That is most of the time not very good style, but it works. In classes you usually change class varbiables from within functions without returning them.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.