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?
yes, you can use an object :-)
but the simplest way is to return an array:
return array('value1','value2','value3','...');
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
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.
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
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.
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).
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.