php · level 2 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Check a file is there, then read it line by line.
Reading a file that does not exist stops PHP with an ErrorException that says Failed to open stream. So check first: gives true when there is a file at that path.
file($path) reads a file into an array, one item per line. Each item keeps its \n on the end, unless you pass the FILE_IGNORE_NEW_LINES. A flag is a constant that switches on an extra behaviour, like FILE_APPEND did.
Then a foreach can work through the lines, as with any array.
<?php
$path = sys_get_temp_dir() . "/shopping.txt";
file_put_contents($path, "bread\nmilk\neggs\n");
if (file_exists($path)) {
$items = file($path, FILE_IGNORE_NEW_LINES);
echo count($items) . " things to buy\n";
foreach ($items as $number => $item) {
echo ($number + 1) . ". $item\n";
}
} Build the path once at the top and reuse it, so every line talks about the same file.
guess first
Read back the high scores. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$path = sys_get_temp_dir() . "/high-scores.txt";
file_put_contents($path, "Ava:120\nBo:95\n");
$lines = file($path, FILE_IGNORE_NEW_LINES);
[$name, $score] = explode(":", $lines[1]);
echo "$name has $score points\n";
your turn
Your turn. Save a film list.
Type three film titles, one in each blank. Run it to save them and read them back as lines.
fix it
The recipe was saved, but it will not load. Fix it.
- Read the error:
Failed to open stream. Which file is line 4 trying to read? - Compare the file name on line 2 with the one on line 4, letter by letter.
- Read from
$pathon line 4, so both lines use the same file, then press run.
nailed it
you can read your files back, line by line. :D
file_existschecks a file is there before you read it.filegives an array with one item per line.FILE_IGNORE_NEW_LINESdrops the\nfrom each line.
new words in your collection
- file_exists
- flag
This lesson isn’t saved. A free account remembers every lesson you finish.