PHP file(): Read a file into an array by lines

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

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

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

php file function

That is, the file() function reads a file into an array, where each line of the file becomes an element of the array. And since there are three lines, the file codescracker.txt contains them; 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 of 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 the above PHP example is:

php file function example

PHP file() Syntax

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

file(filename, flag, context)

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

Note: The filename parameter is used to specify the name of a 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 the context stream.

Advantages of the file() function in PHP

Disadvantages of the file() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!