Hi,
check the age during reading.
Does your code looks like:
Code: Select all
$lines = file('ages1.txt');
foreach($files AS $line)
$ages[] = $line;
$lines = file('ages2.txt');
foreach($files AS $line)
$ages[] = $line;
$lines = file('ages3.txt');
foreach($files AS $line)
$ages[] = $line;
For finding the five persons with the lowest age, there is a much simpler solution, if I understood you right.
Just check the age during reading the files. You create an array with 5 elements (all null). For the items in the array there is a requierement: The have to be sorted, e.g. the lowest age is element 0 ($ages[0]) and the highst is the last element ($ages[5]).
If you then read your text files, you just have to check if the new age is lower than the last element of your array:
Code: Select all
$ages = array(null,null,null,null,null);
$lastIndex = count($ages)-1;
$lines = file("ages1.txt");
foreach($lines AS $line) {
$age = intval($line); //To get the age
if($ages[$lastIndex] == null || $age < $ages[$lastIndex])
insert($age, $ages);
}
If you have now found an age which is lower than the highest age in your array (lower than the last element in the array), you have to insert the age into your array, but in a such way, that the array is kept sorted:
Set the last element to null, then go backwards until you find the right position.
If your array looks like:
10 20 30 40
And the new age is 25:
1. 10 20 30 null
2. 10 20 30 30 | 25 < 30, so increase the index of 30 by 1. It's easier just to copy this element
3. 10 20 25 30 | 25 > 20, so replace the element on index 2 with the new age.
If hope you understand what I mean ^^