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:
1 2 3 4 5 | $file_name = $_FILES[$upload_name]['name']; //echo "testing-".$file_name." "; //$file_name = strtolower($file_name); $file_extension = end(explode('.', $file_name)); // error getting here |
We were getting the error in the line
1 | $file_extension = end(explode('.', $file_name)); |
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:
1 2 | $tmp = explode('.', $file_name); $file_extension = end($tmp); |
2. Adding an extra parenthesis removes the error:
1 | $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:
1 | $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.
muchas gracias me funciono.
Eres bienvenido. Para cualquier trabajo o soporte, puede enviarme un correo electrónico en cualquier momento (amit@astech.solutions).
i liked extra parenthesis trick