Jump to content

Selecting number from a TXT file


soltek

Recommended Posts

here's one way

 

make a text file named numbers.txt same location as this script, or rename it to your text file

<?php
$my_file = "numbers.txt";
if (file_exists($my_file)) {
$data = file($my_file);
$number = $data[rand(0, count($data) - 1)];
echo $number;
} else {
echo "$my_file does not exist";
}
?>

Space is fine

 

untested

<?php 

$data = file_get_contents('yourfile.txt'); // grab the whole file into a variable

$array = explode(' ',$data); // explode the data into an array, by spaces

$max = count($array); // find out how many numbers were returned

echo $array[rand(0,$max)]; // echo out a random value.

?>

It works almost fine.

 

The problem is sometimes it doesnt select anything.

Even in the source code of the rendered page it doesnt print any number.

 

my php code is:

<?php 

$data = file_get_contents('yourfile.txt'); // grab the whole file into a variable

$array = explode(',',$data); // explode the data into an array, by spaces

$max = count($array); // find out how many numbers were returned

echo 'Thizzladen, your lucky number is ', $array[rand(0,$max)]; // echo out a random value.

?>

 

My txt file has this:

 

,00125,14589,

´

 

Any idea?

The commas on the text are there 'cause I thought the problem might be with the space, so I changed to a comma.

Anyway, I also cant generate random numbers, I just need specific ones, those that are in the txt file.

 

I added:

print_r($array)

 

after:

echo $array[rand(0,$max)]

 

And it prints:

 

Array ( [0] => 00125 [1] => 14589 )

or

00125 Array ( [0] => 00125 [1] => 14589 )

or

14589 Array ( [0] => 00125 [1] => 14589 )

 

 

The whole code is:

<?php 

$data = file_get_contents('yourfile.txt'); // grab the whole file into a variable

$array = explode(' ',$data); // explode the data into an array, by spaces

$max = count($array); // find out how many numbers were returned

echo $array[rand(0,$max)]; // echo out a random value.
print_r($array);

?>

And the txt only has those two numbers and one space separating them.

Assuming you're going to use spaces as the separator, that should work just fine, with one change. Since the array indices start at zero, you need to subtract 1 from the count when calculating $max. Without doing that, the possible values would be 0, 1 and 2, but only index numbers 0 and 1 exist, explaining why you were getting empty values. If you had error reporting on, you should have gotten an undefined index warning.

 

$max = count($array) - 1; // find out how many numbers were returned

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.