Saturday, October 31, 2009

PHP: Read the whole file into array

Does anyone know about a function that will read the whole content from a given text file, and return an array which will contains the content from the input file. The array will have each lines at separate rows of the array. I didn't find such kind of function, so I made one for myself. This file reading code may not be the most efficient, but worked for me.

Here is the function, this will take a file name, and return you an array.

function read_file_at_array($file){
$content = file_get_contents($file);
$lines = preg_split('/\n/', $content);
return $lines;

To call the function read_file_at_array(), just provide the file name. For example the below code.

$lines = read_file_at_array("input.txt");

That's it. So simple. But remember, if your file name is too large, this function will not be efficient. I mean to load the whole large file into an array is not a good thing.

1 comment:

A. Retha said...

OMG! No! Just use the file() command!

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...