Only variables should be passed by reference

Sometime we face a unique type of problem during development and we watch the code thoroughly but not find the error where we are getting. ‘Only variables should be passed by reference‘ in $file_extension = end(explode(‘.’, $file_name)) is the same type of problem which does not seem as error in our code and it happens in usual code.

I was trying to get an HTML-based file listing based on code here:

We were getting the error in the line

Only variables should be passed by reference

ERROR:
The problem is, that end requires a reference, because it modifies the internal representation of the array (i.e. it makes the current element pointer point to the last element).

The result of explode('.', $file_name) cannot be turned into a reference. This is a restriction in the PHP language, that probably exists for simplicity reasons.

Solution:
1. Assign the result of explode to a variable and pass that variable to end:

2. Adding an extra parenthesis removes the error:

We can use explode for so many ways but if we want to get only file extension then we can use also:

Like ‘end‘, We can face same type of problem with array_pop, array_shift. So we should keep in mind also this type of error.

Like this Post? Share
  • i liked extra parenthesis trick