Question

Say I have a text file with a bunch of lines (the real text file has a LOT more):

Testing
Test
Another line
Blah
ABCDEFG

How can I remove a random amount of lines from this file with PHP? So that means, I can specify how many lines I want to remove randomly.

From what I know so far, I believe I would have to put the lines in an array, and randomly remove them from there. However, I do not know how to do that. I THINK I might need to use shuffle(), but I just want to be sure.

Was it helpful?

Solution

Thanks to the help in the comments, it seems like I solved my problem!

<?php
$items = file_get_contents("items.txt");
$items = explode("\n", $items);
shuffle($items);
$x = 1;
while ($x <= 800) {
    array_shift($items);
    $x++;
}
print_r($items);
?>

Like the comments stated, I loaded the file, exploded it by each new line, used shuffle() on the items, and ran a while loop using array_shift() to remove the random lines.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top