Tag Archives: Only variables should be passed by reference

[PHP Error]Only variables should be passed by reference

PHP Error: Only variables should be passed by reference

A PHP Error was encountered  
Severity: Runtime Notice  
Message: Only variables should be passed by reference  

$file_name = $_FILES[$upload_name][‘name’];
$file_extension = end(explode(‘.’, $file_name)); //ERROR ON THIS LINE

Reason for error reporting:

Getting the suffix name with the end function points the internal pointer of the array to the last element, while end is a reference to pass the value。

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.

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

Solution:

(1) Define a variable to get the value after explode, then use the end function to:

$parts = explode('.', $file_name);  
$file_extension = end($parts);  

(2) Use substr and strrchr functions to get the file suffix:

$ext = substr( strrchr($file_name, '.'), 1);  

(3) Use the pathinfo function to get the file suffix:

$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);  

The end() function points the internal pointer of the array to the last element and returns the value of that element, if successful