I have this php/html code which loads a random youtube video from a php array each time the page is loaded. But I want to have next and previous buttons to load the next and previous videos in the array. Only a single video must be loaded at any time. I have this:
<?php $videos = array("0jBRY_Aki9s","1czXvHSjDac","1kbiUiRfnh8","377kKBi6anQ");
$rand = array_rand($videos);
$rand_key = $videos[$rand];
$numOfItems = count($videos);
echo "<iframe width='375' height='310'
src='http://www.youtube.com/embed/$rand_key?&fmt=22&autoplay=1'> </iframe>";?>
<span onclick="<?php $clip = next($videos);
echo "<iframe style='float:left;' width='375' height='310'
src='http://www.youtube.com/embed/$clip?&fmt=22&autoplay=1'>
</iframe>";?> ">next</span>
Is there some way to use the php "next" method to do change the current video on the iframe ?
No! You cannot mix PHP
with Javascript
like that, PHP
is server side while Javascript
is client side, based on browser.
You have 2 options, you can use AJAX
to load next video, or use an anchor
to link to next video:
<?php
$videos = array("0jBRY_Aki9s" , "1czXvHSjDac" , "1kbiUiRfnh8" , "1uTypnaP5X4" , "377kKBi6anQ");
$rand = array_rand($videos);
$rand_key = isset($_GET['id']) ? $_GET['id'] : $rand;
echo "<iframe width='375' height='310' src='http://www.youtube.com/embed/".$videos[$rand_key]."?&fmt=22&autoplay=1'> </iframe>";
$next = isset($videos[($rand_key+1)]) ? ($rand_key+1) : 0;
$prev = isset($videos[($rand_key-1)]) ? ($rand_key-1) : count($videos)-1;
?>
<a href="test.php?id=<?php echo $prev; ?>">prev</a> | <a href="test.php?id=<?php echo $next; ?>">next</a>