PHP for reading the contents of a file into an array


Code Solution

<?php
// Read the contents of a file into an array
$file = 'file.txt';
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// Print the contents of the array
print_r($contents);
?>

Explanation

The file() function in PHP is used to read the contents of a file into an array. The function takes two parameters: the name of the file to be read, and a flags parameter that can be used to specify how the file should be read.

The FILE_IGNORE_NEW_LINES flag tells the file() function to ignore newlines when reading the file. This means that the contents of the file will be read into a single array, regardless of how many newlines are present in the file.

The FILE_SKIP_EMPTY_LINES flag tells the file() function to skip empty lines when reading the file. This means that any lines in the file that are empty will not be included in the array.

The print_r() function is used to print the contents of an array in a human-readable format.

Implementation

To implement this code solution, you can follow these steps:

  1. Open the file that you want to read using the fopen() function.
  2. Use the file() function to read the contents of the file into an array.
  3. Use the print_r() function to print the contents of the array.

Here is an example of how to implement this code solution in a PHP script:

<?php
// Open the file
$file = fopen('file.txt', 'r');

// Read the contents of the file into an array
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// Print the contents of the array
print_r($contents);

// Close the file
fclose($file);
?>