Hit refresh several times and see sometimes I get “null”.
This script loops through a folder to get all mp3 files and randomly selects one.
What am I doing wrong? Thanks
if ($handle = opendir('../../hope/upload/php/files/')) {
while (false !== ($entry = readdir($handle))) {
$entry = trim($entry);
if(preg_match('/.mp3/', $entry))
{
$mp3[] = "$entry";
}
}
closedir($handle);
$count = count($mp3);
$rand = rand(0,$count -1); /// FIXED BY adding a -1 after count**
$mp3 = $mp3[$rand];
if($mp3)
{
echo "http://MyWebsite.com/hope/upload/php/files/$mp3";
}
else
{
echo "null";
}
}
This is happening because array indexes go from
0tolength - 1, but your script is generating a random index from0tolength. The preferred way to fix this would be to usearray_rand():