I have a php function I’ve written that sorts player’s fastest race times. However, it’s very dirty, me being a beginning php programmer. I want to know how I could write this much simpler so that only 1 file read is being done:
function write_scores($name, $time)
{
$racetimes = "/home/duke/aa/servers/demo/var/logs/racetimes.txt"; //temporary file
$test = "/home/duke/aa/servers/demo/var/logs/test.txt"; //sorted file
$fh = fopen($racetimes, 'a');
$lines = file($racetimes);
fwrite($fh, "$time, $name\n");
natsort($lines);
$lines = array_slice ( $lines , 0, 5); //only store 100 scores to speed performance although $racetimes is the one that needs trimming...
file_put_contents($test, implode("", $lines));
}
I’ve tried removing the racetimes reference, but then nothing gets written. I can’t wrap my brain around it. How can this be rewritten so that it only uses 1 file call?
That looks a bit weird, writing the file you’re reading. You’d do better to just add the time to the in-memory array, then you could write it out with the other sorted scores.
I took the liberty of removing
$testfrom the function. I’m assuming the goal is to maintain one sorted list of scores. If you really want two, re-add all the references to$test.