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:
$file_name = $_FILES[$upload_name]['name'];
//$file_name = strtolower($file_name);
$file_extension = end(explode('.', $file_name)); // error getting here
We were getting the error in the line
$file_extension = end(explode('.', $file_name));
Only variables should be passed by reference
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.
1. Assign the result of explode to a variable and pass that variable to end:
$tmp = explode('.', $file_name);
$file_extension = end($tmp);
2. Adding an extra parenthesis removes the error:
$file_extension = end((explode('.', $file_name)));
We can use explode for so many ways but if we want to get only file extension then we can use also:
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
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.