×

php · level 2 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.