What would be unsuitable would be writing a whole chunk of code over and over with just the name changing each time.
But it's also expensive to be reading and writing a file over and over with only one name shifting each time. It would make more sense to read the file once, make all of the desired changes, and then write it (once).
That would involve changing the function so that instead of the file name, it took the array of lines read from the file and returned the rearranged lines so that it could be written back out.
Then you'd have the names to shift in an array. Looping through the elements of that array, pass each of them (along with the lines) to the function and get back the rearranged lines, then go on to the next name.
The next idea would be to have that loop inside the function, and pass it both arrays.
One thing is certain: the whole point of having the function is to look for a name and shift it if necessary. Which means that
$lines = array_map('trim', file($file));
$i=0;
while ($i<count($lines))
{
if ($lines[$i]='/john/i' ||$lines[$i]='/peter/i' ) //line_to_change????
{
$lines[$i]=move_name_to_end_of_file($file, $lines[$i]);
$i++;
}
}
pretty much totally ignores what the function does (what would be the point of reading the file, looping through every line to check and maybe move it, and then writing the file if on every line you read the file, looping through every line to check and maybe move it...? Please, read what you're writing and ask yourself honestly if it makes the faintest bit of sense. (Incidentally, you'll notice that using [noparse]
...
[/noparse] around your code gives a better result than single quotes. See the FAQ for more).
But any how, where I left the code was passing it two arrays - one of lines and one of names. That looks like
function move_names_to_end($lines, $names)
{
foreach($names as $name)
{
$lines_mentioning_name = array_keys(preg_grep('/'.preg_quote($name).'/i', $lines));
if(!empty($lines_mentioning_name))
{
$first_line_mentioning_name = $lines_mentioning_name[0];
unset($lines[$first_line_mentioning_name]);
$lines[] = $name;
}
}
return $lines;
}
// And to use it...
$names = array('john', 'peter', 'whatever');
$lines = array_map('trim', file($file));
$lines = move_names_to_end($lines, $names);
file_put_contents($file, join(PHP_EOL, $lines));
Note the absence of all that other cruft - it's been moved into the function. It could be altered further, especially with some added domain knowledge, but it works and is pretty straightforward.