6.6.1. ProblemYou want to return a value by reference, not by value. This allows you to avoid making a duplicate copy of a variable. 6.6.2. SolutionThe syntax for returning a variable by reference is similar to passing it by reference. However, instead of placing an & before the parameter, place it before the name of the function: function &pc_array_find_value($needle, &$haystack) { foreach ($haystack as $key => $value) { if ($needle == $value) { return $haystack[$key]; } } } Also, you must use the =& assignment operator instead of plain = when invoking the function: $html =& pc_array_find_value('The Doors', $artists); 6.6.3. DiscussionReturning a reference from a function allows you to directly operate on the return value and have those changes directly reflected in the original variable. For instance, Example 6-3 searches through an array looking for the first element that matches a value. It returns the first matching value. For instance, you need to search through a list of famous people from Minnesota looking for Prince, so you can update his name. Returning an array value from a function by reference
Without the ability to return values by reference, you would need to return the array key and then re-reference the original array: function pc_array_find_value($needle, &$haystack) { foreach ($haystack as $key => $value) { if ($needle == $value) { return $key; } } } $minnesota = array('Bob Dylan', 'F. Scott Fitzgerald', 'Prince', 'Charles Schultz'); $prince =& pc_array_find_value('Prince', $minnesota); $minnesota[$prince] = 'O(+>'; // The ASCII version of Prince's unpronounceable symbol When returning a reference from a function, you must return a reference to a variable, not a string. For example, this is not legal: function &pc_array_find_value($needle, &$haystack) { foreach ($haystack as $key => $value) { if ($needle == $value) { $match = $haystack[$key]; } } return "$match is found in position $key"; } That's because "$match is found in position $key" is a string, and it doesn't make logical sense to return a reference to non-variables. As of PHP 5, you're warned when you do this. Unlike passing values into functions, in which an argument is either passed by value or by reference, you can optionally choose not to assign a reference and just take the returned value. Just use = instead of =&, and PHP assigns the value instead of the reference. 6.6.4. See AlsoRecipe 6.3 on passing values by reference. |