Return Values
PHP functions can return only a single value with the return keyword:
functionreturnOne(){return42;}
To return multiple values, return an array:
functionreturnTwo(){returnarray("Fred",35);}
If no return value is provided by a function, the function returns
NULL instead.
By default, values are copied out of the function. To return a
value by reference, both declare the function with an & before its name and when assigning the
returned value to a variable:
$names=array("Fred","Barney","Wilma","Betty");function&findOne($n){global$names;return$names[$n];}$person=&findOne(1);// Barney$person="Barnetta";// changes $names[1]
In this code, the findOne()
function returns an alias for $names[1], instead of a copy of its value.
Because we assign by reference, $person
is an alias for $names[1], and the
second assignment changes the value in $names[1].
This technique is sometimes used to return large string or array values efficiently from a function. However, PHP implements copy-on-write for variable values, meaning that returning a reference from a function is typically unnecessary. Returning a reference to a value is slower than returning the value itself.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access