Forum Moderators: coopster

Message Too Old, No Replies

Random $var repeating.

Need it to display different everytime.

         

sauce

12:17 am on Jan 22, 2006 (gmt 0)

10+ Year Member



I'm trying to pull random lines from text file and print them from calling a variable but everytime I call the variable it pritns the same thing. Here is the code:

<?php

$var = file("vars.txt");
$returns = array("\n", "\r");
$var = str_replace($returns, "", $var);
foreach ($var as $num=>$line) {
$var[$num] = strtolower("$line");
}
$n = sizeof($var ) - 1;
$var = $var[rand(1, $n)];

echo $var;
echo $var;
echo $var;
echo $var;
echo $var;
echo $var;

?>

This prints:

line3
line3
line3
line3
line3
line3

When I want it to print each line randomly, like:

line9
line2
line6
line2
line1
line6

Any changes you can see in that code?

thx.

newbie2006

12:31 am on Jan 22, 2006 (gmt 0)

10+ Year Member



<?php

$var = file("vars.txt");
$returns = array("\n", "\r");
$var = str_replace($returns, "", $var);
foreach ($var as $num=>$line) {
$var[$num] = strtolower("$line");
}
$n = sizeof($var ) - 1;
$var_ = $var[rand(1, $n)];
echo $var_;
$var_ = $var[rand(1, $n)];
echo $var_;
$var_ = $var[rand(1, $n)];
echo $var_;
$var_ = $var[rand(1, $n)];
echo $var_;
$var_ = $var[rand(1, $n)];
echo $var_;
?>

Just follow your style, it will be so. But read about delete symbols in the end of line, and you need to look in it more carefully, not the best solution.

sauce

7:09 pm on Jan 22, 2006 (gmt 0)

10+ Year Member



Is there any way I can reset this array after if it executed...

like $var_ = $var[rand(1, $n)] - reset

Instead of having to enter:

$var_ = $var[rand(1, $n)];

everytime I echo $var?

newbie2006

7:30 pm on Jan 22, 2006 (gmt 0)

10+ Year Member



srand((float) microtime() * 10000000);
$keys = array_rand($var, 2);
echo $var[$keys[0]];
echo $var[$keys[1]];

if you try to put here also the foreach cycle, then possibly you will get what you are looking for.