Search code examples
phpkeysequencewriterreader

Key Entry Sequence from file -- PHP


So, I am teaching myself php and I managed to find some pretty basic coding problems to help practice. The one that I am stuck on seems like it has a simple solution. I am using code from a previous problem (a Entry Sequence Create) and turn it into a Key Sequence Create. Basically, the code needs to read in a file, find where a key value belongs in the order of the list, and then insert the record in its respected position.

<?php
//read current file
$studentArray = file("student.txt"); 
echo "Create Key Sequence Student File\n";
echo "Enter ID: ";
$id = rtrim(fgets(STDIN));
echo "Enter FN: ";
$fn = rtrim(fgets(STDIN));
echo "Enter LN: ";
$ln = rtrim(fgets(STDIN));
echo "Enter Major: ";
$maj = rtrim(fgets(STDIN));
echo "Enter Credit Hours: ";
$cHours = rtrim(fgets(STDIN));
//put them in a string
$studentString = "$id".':'."$fn".':'."$ln".':'."$maj".':'."$cHours\n";
//add the string to the array and write array to file
$studentArray[] = $studentString;  
$studentString = implode("",$studentArray);
file_put_contents("student.txt",$studentString);
?>

I have no idea what to do. The text I've found doesn't include anything about a Key Sequence Create formula

10000:Bill:Smith:CPSC:34
10010:Jan:Wilson:CPSC:0
10020:Sue:Sweet:ENGR:231
10030:Li:Chan:BIOL:64
10040:Luis:Gonzales:MATH:90

Is the contents of the value we are reading from. The key we use 10015 (the value id). The code should be able to read over the list and determine where 10015 fits in and then insert the information from the STDIN accordingly.


Solution

  • Why search for it's place? Just insert and sort:

    $studentString = "$id".':'."$fn".':'."$ln".':'."$maj".':'."$cHours\n";
    $studentArray[] = $studentString;  
    sort($studentArray);
    file_put_contents("student.txt",$studentArray);
    

    Also, no need for implode(), as file_put_contents() will do this for you.