0

I have an array that relates mp3 files and their respective lengths in seconds

$playlist = array(  array("song" => "01.mp3","min" => "91"),
                   array("song" => "02.mp3","min" => "101"),
                   array("song" => "03.mp3","min" => "143"),
                   array("song" => "04.mp3","min" => "143"),
                   array("song" => "05.mp3","min" => "151")
            );

The I pluck a song from the playlist with array_rand()...

$song = $playlist[array_rand($playlist)];

Then, later on, I access the values from that array...

echo $song['song'];

//Then somewhere else...

echo $song['min'];

My question is, each time I request $song, is it going to produce a random result, or does it only produce a random result once per page load? (ie, once $song is defined, it's defined for good.) ...I'm hoping it's the latter.

2
  • 1
    $song is assigned only at creation, it will remain the same for the remainder of that request / the variables lifetime. Commented Apr 22, 2013 at 18:36
  • $song value intialize on on page load, not each time Commented Apr 22, 2013 at 18:37

1 Answer 1

1

My question is, each time I request $song, is it going to produce a random result, or does it only produce a random result once per page load?

No, it won't. It will produce a random result every time you call the array_rand function. If you call it once per page load then yes, it will produce only one random result every time a page is loaded.


In general every time you access a variable you are most likely not going to change it in that specific line. In particular, simplifying your example (rand picks a number from the minimum to the maximum specified):

$x = rand(0, 9);

if a number, let's say 7, is picked then multiple accesses to $x will not change its value. Only an explicit $x = y assignment (or passing it to a class or function that has side effect on it) will possibly change its value.

Considering 7 to be picked from rand:

echo $x;
echo $x;
echo $x;

will print 777.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.