September 24, 2017

Core PHP: Reading a File (8.6)

Reading a File


At the end of the output in the previous example, we would have a comma, as we print it after each element of the array.
The following code lets us avoid printing that final comma.
$read = file('names.txt');
$count = count($read);
$i = 1;
foreach ($read as $line) {
  echo $line;
  if($i < $count) {
    echo ', ';
  }
  $i++;
}

The $count variable uses the count function to obtain the number of elements in the $read array.
Then, in the foreach loop, after each line prints, we determine whether the current line is less than the total number of lines, and print a comma if it is.
This avoids printing that final comma, as for the last line, $i is equal to $count.

No comments:

Post a Comment