Finding a random line of a file : mt_rand « Math « PHP






Finding a random line of a file

 
<?php
function randomint($max = 1) {
  $m = 1000000;
  return ((mt_rand(1,$m * $max)-1)/$m);
}
?>

$line_number = 0;

$fh = fopen('data.txt','r') or die($php_errormsg);
while (! feof($fh)) {
    if ($s = fgets($fh)) {
        $line_number++;
        if (randomint($line_number) < 1) {
            $line = $s;
        }
    }
}
fclose($fh) or die($php_errormsg);
?>
  
  








Related examples in the same category

1.int mt_rand ( [int min, int max] ) returns random numbers, similar to the rand( ).
2.Generate random floating-point values from 0 to 10 with two decimals
3.Generate random numbers
4.Get a random value from 5 to 25.
5.Generate Password()
6.Get random values from –10 to 10.
7.Random floating-point values from 0 to 10 with two decimals
8.Random numbe with precision
9.Random values are not restricted to positive integers. The following example shows how to get random values from -10 to 10.