Randomized Youtube App

This lighthearted exercise doesn’t require you to do much but it’s kind of fun and offers a bit more information about arrays and php’s ‘random’ feature.

1. Revisit free.mynmi.net. Find the file named babies.php and click on it. A baby video should pop up from youtube. Like that baby? If not, click the button below to see a different, randomly generated, baby video.

2. Should you ever become tired of baby videos, download babies.zip from free.mynmi.net, decompress it, and open babies.php with Brackets.

3. Take a look at the code. As you see, the whole thing begins with and array named babies, as in $babies = Array (, and there are lots of babies in that array. Each of those random collections of letters, symbols, and numbers, such as _JmA2ClUvUY, corresponds to a unique youtube video.   You could count them but php offers an easier way.

4. Take a look at line 15 where the variable $numberOfBabies = sizeof($babies); That’s php for tell me how many baby videos are in that array.

5. On line 16 we actually take the variable $numberOfBabies and embed it into a sentence.

6. Take a look at line 18 where, for some odd reason, we subtract one from $numberOfBabies. The reason for this odd behavior is because we want to extract random numbers from the array that correspond to a given video but there is a problem: Arrays begin at 0, which means that even though there are 12 videos on that array, if the random number generator spits out 12, we have a problem. As far as that array is concerned, element 12 corresponds to the number 11.   Did that make sense?

7. Now take a look at line 21 where the random numbers are generated. This line, which reads,  $which= rand (0, $arrayNum);, generates a random number from 0 to whatever the value of $arrayNum happens to be. We could replace $arrayNum with 11 and everything would work just the same unless we add or subtract elements from the array. 

8. Lines 27 and 29 echo out the embed information that applies to all youtube videos, while line 26 grabs a random value from the array that corresponds to a given youtube video.

9. And that’s it!  If you want to play a little bit, add those three extra baby videos on line 34 to the array and test it out on your server.

Next: Extras