[php] "Strict Standards: Only variables should be passed by reference" error

I am trying to get an HTML-based recursive directory listing based on code here:

http://webdevel.blogspot.in/2008/06/recursive-directory-listing-php.html

Code runs fine but it throws some errors:

Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\directory5.php on line 34

Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\directory5.php on line 32

Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\directory5.php on line 34

Below is the excerpt of code:

else
  {
   // the extension is after the last "."
   $extension = strtolower(array_pop(explode(".", $value)));   //Line 32

   // the file name is before the last "."
   $fileName = array_shift(explode(".", $value));  //Line 34

   // continue to next item if not one of the desired file types
   if(!in_array("*", $fileTypes) && !in_array($extension, $fileTypes)) continue;

   // add the list item
   $results[] = "<li class=\"file $extension\"><a href=\"".str_replace("\\", "/",     $directory)."/$value\">".$displayName($fileName, $extension)."</a></li>\n";
  }

This question is related to php

The answer is


array_shift the only parameter is an array passed by reference. The return value of explode(".", $value) does not have any reference. Hence the error.

You should store the return value to a variable first.

    $arr = explode(".", $value);
    $extension = strtolower(array_pop($arr));   
    $fileName = array_shift($arr);

From PHP.net

The following things can be passed by reference:

- Variables, i.e. foo($a)
- New statements, i.e. foo(new foobar())
- [References returned from functions][2]

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:


I had a similar problem.

I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.

Let's say for example this one.

$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');

// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));

// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should 
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut 
// down the process one by one like this.

$data1  = array_keys($data);
$lastkey = array_pop($data1);

echo $lastkey;

There you go!


Instead of parsing it manually it's better to use pathinfo function:

$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];