Reputation: 3828
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";
}
}
Upvotes: 1
Views: 105
Reputation: 490303
You random range is out (the max integer is the result of count()
, and remember the count of an array is one higher than its highest index in an ordinal 0-based array), and your code looks far too verbose.
Try...
$mp3s = glob('../../hope/upload/php/files/*.mp3');
$key = array_rand($mp3s);
$randomMp3 = $mp3s[$key];
Upvotes: 1
Reputation:
This is happening because array indexes go from 0
to length - 1
, but your script is generating a random index from 0
to length
. The preferred way to fix this would be to use array_rand()
:
$rand = array_rand($mp3);
$mp3 = $mp3[$rand];
Upvotes: 2