I want to echo random lines by PHP from file sitemap.txt
that provide as:
link1
link2
link3
link4
...
link10000
I have tried using this function:
$lines = file("sitemap.txt");
$data[link] = $lines[array_rand($lines)];
But this $data[link]
will echo output 1 random value only such as link1 or link10000
However, I need to echo 100 random values from sitemap.txt
How can I optimize this function?
Thanks
You can use shuffle and array_slice.
$lines = file("sitemap.txt");
Shuffle($lines);
Echo implode("<br>", array_slice($lines, 0, 100));
This will shuffle the links and extract 100 of then and echo them one on each line.
Using non looping solutions is the fastest method for this type of problem.
See simple example here: https://3v4l.org/Oqnot
$lines = file("sitemap.txt");
$data = array_rand($lines, 100);
foreach($data as $value) {
echo $lines[$value]."<br>";
};
output is like upto 100 lines.
link3
link4
..
..
You could try using shuffle function to mix values inside array. And then use array_pop function in for loop.
shuffle($lines);
for ($i = 0; $i < 100; $i++) {
echo $lines[$i];
}
you could try this one
$array=array(); // declaration of array
$array=explode("\n", file_get_contents('new.txt')); // get the text file
shuffle($array); // where array shuffles inside the array
// below just to show if array is already shuffles
foreach($array as $a){
echo $a;
}
//end code
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.