Jump to content

[SOLVED] How to get a random value for each instance of a for loop?


blurredvision

Recommended Posts

I'm wanting to write multiple lines to a text file, but randomize one of the values on each line, but I don't know how to get it to work.  With the following code, it can get it to choose a random value from $modarray, but it uses that one value through the entire fwrite, whereas I'd like for it to grab a new value for each line it writes to the text file.

 

Here is a snippet of the code I'm trying to use:

$modarray = array (
0 => 'value1',
1 => 'value2',
2 => 'value3',
3 => 'value4'
);

$modcount = count($modarray);
$modrand = rand(0, ($modcount - 1));

for($i = 0; $i < $repeatlength; $i++) {
$randommod = ($modarray[$modrand]);
fwrite($fh, $variable1 . "," . $variable2 . "," . $variable3 . "," . $randommod . "," . $variable4 . "," . $variable5 . "\r\n");
}

 

Variables 1 through 5 are specified earlier in the script, and aren't important to the issue here.  The $repeatlength variable will specify how many times this line is written to the text file.

 

Is there a way to get it to "reinitialize" the $randommod variable with a new value each time it runs the loop?  I've tried putting the ($modarray[$modran]) in different places; inside the for loop (as shown), before even starting the loop, and using it directly in the fwrite command, and I get the same results every time.  If I'm way off base with my methodology, how can I get this to work?

 

Thanks for any help.  If I didn't explain well enough, my apologies, I'll try to answer any questions.

exactly - like this

 

for($i = 0; $i < $repeatlength; $i++) {

            $modrand = rand(0, ($modcount - 1));

$randommod = ($modarray[$modrand]);

fwrite($fh, $variable1 . "," . $variable2 . "," . $variable3 . "," . $randommod . "," . $variable4 . "," . $variable5 . "\r\n");

}

No need to "count" the number of values in the array. array_rand() will return the index of a random value in an array.

 

<?php

$modarray = array (
   0 => 'value1',
   1 => 'value2',
   2 => 'value3',
   3 => 'value4'
);

for($i = 0; $i < $repeatlength; $i++) {
   $randommod = $modarray[array_rand($modarray)];
   fwrite($fh, $variable1 . "," . $variable2 . "," . $variable3 . "," . $randommod . "," . $variable4 . "," . $variable5 . "\r\n");
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.