I am trying to get this php code to search ALL the directories on my site for images. I then want is to store the image names and directories in an array and display one random picture.

My problem is that it seems to erase the contents of the array everytime it searches a new directory, and is completely empty by the time is tries to run the random function. I would appreciate any tips on how I can solve this problem.
Thanks

<?php
$basedir =  "/home/vsites/velcron/public_html/php/archive/";
$result = $dirfiles = $dirnames = array();
$target="_blank";
function listall($dir)
{
      // temp arrays
    $dir_files = $dir_subdirs = $dir_names = array();
    chdir($dir);
    $handle = @opendir($dir) or die( "Directory \"$dir\"not found.");

 // loop through all directory entries 
while($entry = readdir($handle)) 
{
    if(is_dir($entry) && $entry !=  ".." && $entry !=  ".")
    {
        $dir_subdirs[] = $entry;
    }
    elseif($entry !=  ".." && $entry !=  ".")
    {   
        if (ereg(".gif",$entry) || ereg(".jpg",$entry) || ereg(".JPG",$entry) || ereg(".GIF",$entry)) 
    { 
		$dir_names[] = $dir;
		$dir_files[] = $entry;
		$foo = substr("$dir", 33);
		$a ="http://www.buttonyourpants.com/". $foo ."". $entry;
		$result = array_merge_recursive ($result, $a);
		}
	}
}

 // sub directories
for($i=0; $i<count($dir_subdirs); $i++)
{
    listall( "$dir$dir_subdirs[$i]/");
}

// displays all images
//	for($i=0; $i<count($result); $i++)
//   {
//		echo "<br><img src=\"$result[$i]\">";
//   }

closedir($handle);
}

// display random image??
function randompic($result)
{
	$random_no= count($result);
	$random=$random_no-1;
	mt_srand ((double) microtime () * 1000000);
	$rnd= mt_rand(0,$random);
	echo "<br><img src=\"$result[$rnd]\">";
}

listall($basedir);
randompic($result);
?>

    $dir_files = $dir_subdirs = $dir_names = array();

    The above references the same variable. You may be over-writing the variable.

    try

    $dir_files = array();
    $dir_subdirs = array();
    $dir_names = array();

    instead.

      After changing the code to that, I still get an empty array with html code of <img src="">

        You never return the value of $result from the function listall.

        Read PHP's documentation on the subject of variable scope - variables aren't automatically global.

        In response to chingwaah's post: $dir_files, $dir_subdirs, and $dir_names are all separate variables, since none are being passed by reference - so changes to one won't affect the others, as a quick experiment

        $dir1 = $dir2 = array();
        $dir1[]='hello world';
        $dir2[]='goodbye cruel world';
        print_r($dir1);
        print_r($dir2);
        

        would show.

        Return $results from the listall function, and pick it up in the main body of the script with $results=listall($basedir);

          I got it to work after I declared the variable!!!

            Write a Reply...