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("fresherearth.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 fresherearth.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("fresherearth.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:

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

PHP Online Test


« Previous Tutorial Next Tutorial »