In: Computer Science
The accompanying 2 files (boynames.txt and girlnames.txt) contain the results of a recent census of boy and girl births in the last year. Each record of the files contain a given name and the number of new born children receiving that name. E.g.,
Matthew 23567 or Alison 17658
Each name is separated from the number by a blank space.
There are also some common names given to both boys and girls, e.g., Riley. They will appear in both the boy file and the girl file.
Write a PHP script that finds answers to the following questions.
The code for above question is:
<?php 
// saving the file pointer of the girls
$girlnames = fopen("girlnames.txt", "r") or die("Unable to open file!"); 
// saving the file pointer of the boys
$boynames = fopen("boynames.txt", "r") or die("Unable to open file!");
$total_girls = 0;
while(!feof($girlnames)) {
        // fgets() get input line by for the file
        // explode splits the input in array of the form ['name', 'count']
        $single_girl = explode(" ", fgets($girlnames));
        // storing as a key value pair where $girl['name'] = 'count'; 
        $girl[$single_girl[0]] = $single_girl[1]; 
        // get the total number of girls by adding the count
        $total_girls = $total_girls + (int)($single_girl[1]); 
}
$total_boys = 0;
while(!feof($boynames)) {
        // fgets() get input line by for the file
        // explode splits the input in array of the form ['name', 'count']
        $single_boy = explode(" ", fgets($boynames));
        // storing as a key value pair where $boy['name'] = 'count'; 
        $boy[$single_boy[0]] = $single_boy[1];
        // get the total number of boys by adding the count
        $total_boys = $total_boys + (int)($single_boy[1]);
}
$count = 0;
// getting the table ready for the output
$data = "<table><tr><th>Name</th><th>Girl count</th><th>Boy count</th></tr>";
foreach ($girl as $key => $value) {
        // name present in both girl and boy
        if (array_key_exists($key, $boy)) { 
                $count++; // count of common names
                // apending the result for the table data
                $data = $data."<tr><td>".$key."</td><td>".$value."</td><td>".$boy[$key]."</td></tr>";
        }
}
// ending with /table
$data = $data."</table>"; 
// printing output as required
echo("The total common names between boys and girls are : <b>".$count."</b><br>");
echo($data);
echo("The total number of girls born last year : <b>".$total_girls."</b><br>");
echo("The total number of boys born last year : <b>".$total_boys."</b><br>");
?>
girlnames.txt:
Reny 235222
Martha 123222
Riley 122212
Aarnav 12332
girlnames.txt(image):

boynames.txt:
Alison 17623
Aarnav 23433
Riley 12423
boynames.txt(image):

Output for the given boynames.txt and girlnames.txt:
