I have 2 sets of code, which both work on their own, but I need to combine them both, and havent been able to do it.
The end result should be to display a text file, line by line, with array #, alphabetically (and therefore array numbers should display at the end of each line).
FIRST PIECE OF CODE
<?php
$filename="users.txt";
$lines = array();
$file = fopen($filename, "r");
while(!feof($file)) {
$lines[] = fgets($file,4096);
}
natcasesort($lines);
$text = implode("<br />", $lines);
print_r($text);
fclose ($file);
?>
SECOND PIECE OF CODE
<?php
$lines = file('users.txt');
foreach ($lines as $line_num => $line)
{
print "<font color=red>Line #{$line_num}</font> : " . $line . "<br />\n";
}
?>
There are two easy ways to do this. This one will only work for PHP >= 5.4.0:
If using an earlier version, you can achieve the same effect with
uasortandstrnatcasecmp:See it in action.
In both case the idea is to use a sort function that maintains index association, so that after the lines are sorted they remain indexed by their original key (which is the line number in the file). Both
usortanduasortdo this;uasortallows you to specify the sort comparison function yourself whileusortonly allows a few built-in options (which do not include natural sorting in PHP < 5.4).As an aside: please do not use the
<font>tag ever again.