Categories
Uncategorized

What does “only variables should be passed by reference” mean?

$sentence = "Once upon a time";
$first_word = reset(explode(" ", $sentence));
// ^ PHP Notice:  Only variables should be passed by reference in php shell code on line 1

What? Your code works; $first_word is now "Once" just like you expected. But PHP, for some reason, doesn’t like what you’re doing.

The reason for the error is subtle, and is to do with reset‘s behaviour. The function actually does two things; it returns the first item in the passed array, which is the behaviour we need in this case. But it also resets the array’s internal pointer to its first element: This pointer records a position in an array and is used when looping over it, for example.

In order to do this second action, reset needs to know where the array lives in memory; this information is normally given at a programming level by the array variable’s name. Since here we are passing the result of another function (explode) the array does not have a variable name for reset to act on. You can see this more clearly if you try:

$first_word = reset(["Once", "upon", "a", "time"]);

You’ll get the same error.

One option to fix this is to store your explodeed array in a temporary variable and call reset on that:

$sentence = "Once upon a time";
$sentence_parts = explode(" ", $sentence);
$first_word = reset($sentence_parts);

This will work just fine, as reset has a variable name to work on.

Another option which makes for cleaner code, but might confuse newcomers to your codebase, is to create a helper function:

function first(array $arr) {
    return reset($arr);
}

$sentence = "Once upon a time";
$first_word = first(explode(" ", $sentence));

Your unnamed array recieves a name ($arr) when it is passed to the function first, so reset can act on it with no problems.

The resetting of the array’s internal pointer is known as a side effect: There are many PHP array_ functions that have affects on the array’s internal pointer. If you want to avoid this, copying the array to a temporary variable or creating a helper function are useful tools to have.

Your email will not be given to anyone else, ever.