|
3 | 3 | // Create array to hold list of todo items
|
4 | 4 | $items = array();
|
5 | 5 |
|
6 |
| -// The loop! |
7 |
| -do { |
| 6 | +// List array items formatted for CLI |
| 7 | + // Return string of list items separated by newlines. |
| 8 | + // Should be listed [KEY] Value like this: |
| 9 | + // [1] TODO item 1 |
| 10 | + // [2] TODO item 2 - blah |
| 11 | + // DO NOT USE ECHO, USE RETURN |
| 12 | + |
| 13 | +function list_items($list) { |
| 14 | + $place = ''; |
8 | 15 | // Iterate through list items
|
9 |
| - foreach ($items as $key => $item) { |
10 |
| - $key++; |
11 |
| - // Display each item and a newline |
12 |
| - echo "[{$key}] {$item}\n"; |
| 16 | + foreach ($list as $key => $item) { |
| 17 | + $place .= "[" . ++$key . "]" . " " . $item . PHP_EOL; |
| 18 | + // Display each item and a newline |
| 19 | + } |
| 20 | + return $place; |
| 21 | +} |
| 22 | + |
| 23 | +// Get STDIN, strip whitespace and newlines, |
| 24 | +// and convert to uppercase if $upper is true |
| 25 | +function get_input($upper = FALSE) { |
| 26 | + // Return filtered STDIN input |
| 27 | + if($upper == TRUE) { |
| 28 | + return strtoupper(trim(fgets(STDIN))); |
| 29 | + } else { |
| 30 | + return trim(fgets(STDIN)); |
13 | 31 | }
|
| 32 | +} |
| 33 | + |
| 34 | +// The loop! |
| 35 | +do { |
| 36 | + // Echo the list produced by the function |
| 37 | + echo list_items($items); |
14 | 38 |
|
15 | 39 | // Show the menu options
|
16 | 40 | echo '(N)ew item, (R)emove item, (Q)uit : ';
|
17 | 41 |
|
18 | 42 | // Get the input from user
|
19 | 43 | // Use trim() to remove whitespace and newlines
|
20 |
| - $input = trim(fgets(STDIN)); |
| 44 | + $input = get_input(true); |
21 | 45 |
|
22 | 46 | // Check for actionable input
|
23 | 47 | if ($input == 'N' || $input == 'n') {
|
24 | 48 | // Ask for entry
|
25 | 49 | echo 'Enter item: ';
|
26 | 50 | // Add entry to list array
|
27 |
| - $items[] = trim(fgets(STDIN)); |
| 51 | + $items[] = get_input(); |
28 | 52 | } elseif ($input == 'R' || $input == 'r') {
|
29 | 53 | // Remove which item?
|
30 | 54 | echo 'Enter item number to remove: ';
|
31 | 55 | // Get array key
|
32 |
| - $key = trim(fgets(STDIN)); |
| 56 | + $key = get_input(); |
33 | 57 | // Remove from array
|
34 | 58 | unset($items[--$key]);
|
35 | 59 | }
|
|
0 commit comments