O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required