Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only variables should be passed by reference

Tags:

php

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

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

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.


Php 7 compatible proper usage:

$fileName      = 'long.file.name.jpg';
$tmp           = explode('.', $fileName);
$fileExtension = end($tmp);

echo $fileExtension;
// jpg

Everyone else has already given you the reason you're getting an error, but here's the best way to do what you want to do: $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);


save the array from explode() to a variable, and then call end() on this variable:

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

btw: I use this code to get the file extension:

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

where strrchr extracts the string after the last . and substr cuts off the .


Try this:

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

The reason is that the argument for end is passed by reference, since end modifies the array by advancing its internal pointer to the final element. If you're not passing a variable in, there's nothing for a reference to point to.

See end in the PHP manual for more info.


Since it raise a flag for over 10 years, but works just fine and return the expected value, a little stfu operator is the goodiest bad practice you are all looking for:

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

But warning, don't use in loops due to a performance hit. Newest version of php 7.3+ offer the method array_key_last() and array_key_first().

https://www.php.net/manual/en/function.array-key-last.php

                 uuuuuuu
             uu$$$$$$$$$$$uu
          uu$$$$$$$$$$$$$$$$$uu
         u$$$$$$$$$$$$$$$$$$$$$u
        u$$$$$$$$$$$$$$$$$$$$$$$u
       u$$$$$$$$$$$$$$$$$$$$$$$$$u
       u$$$$$$$$$$$$$$$$$$$$$$$$$u
       u$$$$$$"   "$$$"   "$$$$$$u
       "$$$$"      u$u       $$$$"
        $$$u       u$u       u$$$
        $$$u      u$$$u      u$$$
         "$$$$uu$$$   $$$uu$$$$"
          "$$$$$$$"   "$$$$$$$"
            u$$$$$$$u$$$$$$$u
             u$"$"$"$"$"$"$u
  uuu        $$u$ $ $ $ $u$$       uuu
 u$$$$        $$$$$u$u$u$$$       u$$$$
  $$$$$uu      "$$$$$$$$$"     uu$$$$$$
u$$$$$$$$$$$uu    """""    uuuu$$$$$$$$$$
$$$$"""$$$$$$$$$$uuu   uu$$$$$$$$$"""$$$"
 """      ""$$$$$$$$$$$uu ""$"""
           uuuu ""$$$$$$$$$$uuu
  u$$$uuu$$$$$$$$$uu ""$$$$$$$$$$$uuu$$$
  $$$$$$$$$$""""           ""$$$$$$$$$$$"
   "$$$$$"                      ""$$$$""
     $$$"                         $$$$"