PHP file() | Read File into an Array by Lines

The PHP file() function is used when we need to get the whole content of a file as/in an array. For example:

<?php
   $x = file("codescracker.txt");
   print_r($x);
?>

The output of above PHP example on file() function is:

php file function

That is, the file() function reads a file into an array, where each line of the file will become the element of array. And since there are three lines, the file codescracker.txt contains, therefore we have seen the above output.

Also, if we write:

echo $x[0];

Or,

print_r($x[0]);

We will get the same output using both the above statements, that will be the first line of the file. For example:

<?php
   $x = file("codescracker.txt");
   echo $x[0];
   echo "<br>";
   echo $x[1];
   echo "<br>";
   echo $x[2];
?>

Now the output of above PHP example, is:

php file function example

PHP file() Syntax

The syntax of file() function in PHP, is:

file(filename, flag, context)

The first (filename) parameter is required, whereas the last two (flag and context) parameters are optional.

Note - The filename parameter is used to specify the name of file along with its extension, available in the current directory (the directory where the PHP code to read the file using file() is saved)

Note - The flag parameter is used to specify the flag value using:

  • FILE_USE_INCLUDE_PATH - Used when we need to search the file in the include_path (in PHP.ini)
  • FILE_IGNORE_NEW_LINES - Used when we need to omit newline at the end of each element
  • FILE_SKIP_EMPTY_LINES - Used when we need to omit empty lines

Note - The context is used when we need to specify the resource of context stream.

PHP Online Test


« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋