Look up values by key: the job associative arrays are made for.
What to build
A program that answers phone book questions.
Requirements
- Read n, then n lines with a name and a number. If a name appears twice, the later number wins.
- Read q, then q lines with a name. For each, print the number, or
not found.
Input
Line 1: n. Then n lines name number. Then q. Then q lines with one name each.
Output
q lines.
Constraints
1 ≤ n, q ≤ 50; names are single words.
Example
Input:
2
Ada 555-0100
Linus 555-0199
2
Ada
Bo
Output:
555-0100
not found
Why it works
A key lookup is direct, and the ?? operator gives the default text for a missing name.
Examples
Example 1 · Input
2 Ada 555-0100 Linus 555-0199 2 Ada Bo
Expected output
555-0100 not found
Example 2 · Input
1 Grace 12345 1 Grace
Expected output
12345
Hints
Hint 1
Store each number with the name as the key.
Hint 2
Use $book[$name] ?? "not found" to answer a question.
Solution
Show one correct solution (try it yourself first)
<?php
$n = (int) trim(fgets(STDIN));
$book = [];
for ($i = 0; $i < $n; $i++) {
[$name, $number] = explode(" ", trim(fgets(STDIN)));
$book[$name] = $number;
}
$q = (int) trim(fgets(STDIN));
for ($i = 0; $i < $q; $i++) {
$name = trim(fgets(STDIN));
echo $book[$name] ?? "not found", "\n";
}