Return Values

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

    function return_one(  ) {
       return 42;
    }

To return multiple values, return an array:

    function return_two (  ) {
       return array("Fred", 35);
    }

By default, values are copied out of the function. A function declared with an & before its name returns a reference (alias) to its return value:

    $names = array("Fred", "Barney", "Wilma", "Betty");
    function & find_one($n) {
       global $names;
       return $names[$n];
    }
    $person =& find_one(1);           // Barney
    $person = "Barnetta";             // changes $names[1]

In this code, the find_one( ) 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’s copy-on-write/shallow-copy mechanism usually means that returning a reference from a function is not necessary. There is no point in returning a reference to some large piece of data unless you know you are likely to change that data. The drawback of returning the reference is that it is slower than returning the value and relying on the shallow-copy mechanism to ensure that a copy of that data is not made unless it is changed.

Get Programming PHP, 2nd 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.