Return Values

PHP functions can return only a single value with the return keyword:

function returnOne()
{
  return 42;
}

To return multiple values, return an array:

function returnTwo()
{
   return array("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.

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.