I’ve been using this code for quite a long time and it has been working for me most of the time. What it does is that it reads a directory (“uploads” in this example) and store every sub-directories that it can find into an array $year[].
$dir = "uploads";
$yeardh = opendir($dir);
while (false !== ($yeardir = readdir($yeardh)))
{
if ($yeardir != '.' and $yeardir != '..' and strtolower(substr($yeardir,strlen($yeardir)-3,3)) != '.db')
{
$year[] = $dir.'/'.$yeardir;
}
}
closedir($yeardh);
It was only recently that I tested and found out that it failed under “certain circumstances” showing the following error message.
Fatal error: [] operator not supported for strings in file.php on line xx
It’s basically complaining about the array $year[]. In order to correct the problem so that it won’t fail under that “certain circumstances”, I’ve made the following changes.
$dir = "uploads";
$yeardh = opendir($dir);
$year = array();
while (false !== ($yeardir = readdir($yeardh)))
{
if ($yeardir != '.' and $yeardir != '..' and strtolower(substr($yeardir,strlen($yeardir)-3,3)) != '.db')
{
$temp = $dir.'/'.$yeardir;
array_push($year, $temp);
}
}
closedir($yeardh);
The change is basically to do with the the array $year. The second version of the code defines the array $year before the loop, and later appends each sub-directory that it can find into the array $year using the PHP function array_push. Tested and it functioned perfectly.
I’m really not sure why it can fail at the first place. If you know why, please let me know by leaving a comment or contact me.
Niels Bom says
The error PHP gives is fairly clear imho, the operator “[]” is not supported for strings. That means that you’re trying to use the [] operator on a variable that is a string.
My guess is that with the first code you /assume/ that $year is either not set, OR an array. There is a third option: $year IS set and it’s a string. That option most probably occured in your script.
I had the same problem today. You are right in your solution of initializing the variable as an empty array before using it as such. This will prevent the error.