Course Content
State Management
0/1
Regular Expressions?
0/1
About Lesson

Read a file into an array:

To read the contents of a file into an array in PHP, you can use the file() function. This function reads the entire contents of a file into an array, with each line of the file as an element in the array. Here’s how you can use it:

PHP
<?php

$lines = file('example.txt');

foreach ($lines as $line) {

    echo $line;

}

?>

In this example:

  • example.txt is the name of the file you want to read.
  • The file() function reads the contents of the file and stores each line as an element in the $lines array.
  • You can then iterate through the array using a foreach loop and perform any desired operations with each line.

Error Handling:

You can add error handling to check if the file was read successfully:

PHP
<?php

$lines = file('example.txt');

if ($lines !== false) {

    foreach ($lines as $line) {

        echo $line;

    }

} else {

    echo "Error reading file.";

}

?>

This way, you can handle cases where the file doesn’t exist or there was an error while reading the file. Make sure the file path is correct and the file is accessible by the PHP script.