Reputation: 19
I'm trying to display a random YouTube video on refresh of my page but it doesn't work. I have the PHP that is working here:
<?php
$video_array = array
('http://www.youtube.com/embed/rMNNDINCFHg',
'http://www.youtube.com/embed/bDF6DVzKFFg',
'http://www.youtube.com/embed/bDF6DVzKFFg');
$total = count($video_array);
$random = (mt_rand()%$total);
$video = "$video_array[$random]";
?>
that I'm trying to put into this:
<iframe width='1006' height='421' src='<?php echo $video; ?>' frameborder='0' allowfullscreen></iframe>
but it seems like it's not working. Could you guys help me out? Thanks! I've been looking for 2 hours and got the same bad results.
Upvotes: 1
Views: 1153
Reputation: 57
Try this code...
<?php
$video_array = array
('http://www.youtube.com/embed/rMNNDINCFHg',
'http://www.youtube.com/embed/bDF6DVzKFFg',
'http://www.youtube.com/embed/bDF6DVzKFFg');
$total = count($video_array);
$random = rand(0, $total-1);
$video = $video_array[$random];
?>
Upvotes: 0
Reputation: 5371
I'm all about one-liners :x
<?php echo $video_array[rand(0,(count($video_array)-1))]; ?>
Other answers thus far are not reducing count()... this will cause errors when it grabs the highest number, as the beginning index==0
Upvotes: 0
Reputation: 3461
<?php
$video_array = array
('http://www.youtube.com/embed/rMNNDINCFHg',
'http://www.youtube.com/embed/bDF6DVzKFFg',
'http://www.youtube.com/embed/bDF6DVzKFFg');
shuffle($video_array);
$video = $video_array[0];
?>
then you can just embed it.
<iframe width='1006' height='421' src='<?php echo $video; ?>' frameborder='0' allowfullscreen></iframe>
Upvotes: 2
Reputation: 2604
Not sure what why you are doing this:
$video = "$video_array[$random]";
Make that look like this
$video = $video_array[$random];
Upvotes: 0