Reputation: 23178
I have a file of highscores for a game I'm scripting. Unfortunately, it takes a lot of memory when I turn the file into and array with file(). Is it possible to limit the size of the file to 100 lines?
Upvotes: 1
Views: 216
Reputation: 530
I agree with the above answer, and I can't comment yet....
If you want to offset the slice, you can use [array_slice($array, offset, 100)
]. So, according to the array_slice man page, if the $array is (a, b, c, d), then $array_slice($array, 2, 2);
would return c, d
.
You could also alter or add code to your application and make it so that users only see their scores, thus increasing the number of files but reducing the overall file size. You should probably just slice high scores to the top 10, 20, or top 100, though. I don't think anyone but the person who wins the score cares who came in 97th place.
You could also use the filesize()
function. Set up a conditional so that if the file is over a maximum size, you slice it, create a new file, and delete the original.
Upvotes: 2
Reputation: 77034
Sure, if you want to keep only 100 lines on disk, only write 100 lines. Suppose you have an array before you write, you can do this with array_slice($array, 0, 100)
.
If you don't have an array before you write, and you only add a few lines each time, you can keep the line count down by slicing at the beginning, just after you read the file.
For both of these suggestions, I'm assuming the array is sorted so the "top" 100 is sequentially at the beginning of the array.
Upvotes: 2