PHP Array Fatal Error
Posted in Software Development, Tips, Hacks, Tricks, Web Development on Feb 24, 2008
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.




































No comments yet.