Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
$song is assigned only at creation, it will remain the same for the remainder of that request / the variables lifetime. – Wrikken Apr 22 at 18:36
SCORE! Thank you. – tPlummer Apr 22 at 18:36
$song value intialize on on page load, not each time – Tamil Selvan Apr 22 at 18:37

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.