Page 1 of 1
Read Text File Into Array
Posted: Tue Jan 23, 2007 3:49 am
by djwk
Hi there
I have a text file named "array.dat" and it contains the following:
7
3
9
10
4
3
1
8
2
How can I load this text file into an array? (Seperated by lines)
Posted: Tue Jan 23, 2007 4:27 am
by dibyendrah
To put everything into array with new lines :
Code: Select all
<?php
$handle = @fopen("array.dat", "r");
if ($handle) {
while (!feof($handle)) {
$buffer .= fgets($handle, 4096);
}
$arr[] = $buffer;
fclose($handle);
}
print_r($arr);
?>
Output :
Code: Select all
Array
(
[0] => 7
3
9
10
4
3
1
8
2
)
To put lines into an array :
Code: Select all
<?php
$handle = @fopen("array.dat", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
$arr[] = $buffer;
}
fclose($handle);
}
print_r($arr);
?>
Output :
Code: Select all
Array
(
[0] => 7
[1] => 3
[2] => 9
[3] => 10
[4] => 4
[5] => 3
[6] => 1
[7] => 8
[8] => 2
)
Posted: Tue Jan 23, 2007 4:45 am
by Mordred
Posted: Tue Jan 23, 2007 5:56 am
by AcidRain
don't forget to trim array's contents
Posted: Wed Jan 24, 2007 4:26 am
by dibyendrah
This will put everything in a variable, not in array.
Posted: Wed Jan 24, 2007 4:49 am
by Mordred
dibyendrah wrote:
This will put everything in a variable, not in array.
Oh, really, you have tried it then? (insert orly owl pic here

)
@
AcidRain: You are quite right that the new lines will remain in the array elements, here's a quick (but good) fix for that:
Code: Select all
function ArrayTrim(&$value){$value=trim($value);}
$arr = file('array.dat');
array_walk($arr, 'ArrayTrim');
(Using array_walk() is a bit longer, but shoule be better in execution time than using array_map(), because it works in-place and does not copy the array)
Code: Select all
$arr = file('array.dat');
$arr = array_map('trim', $arr);
or even:
Code: Select all
$arr = array_map('trim', file('array.dat'));
Posted: Wed Jan 24, 2007 5:47 am
by dibyendrah
Mordred wrote:dibyendrah wrote:
This will put everything in a variable, not in array.
Oh, really, you have tried it then? (insert orly owl pic here

)
Sometimes, brain don't work anymore. yes. $arr becomes array after using file() function.