Read Text File Into Array
Moderator: General Moderators
Read Text File Into Array
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)
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)
- dibyendrah
- Forum Contributor
- Posts: 491
- Joined: Wed Oct 19, 2005 5:14 am
- Location: Nepal
- Contact:
To put everything into array with new lines :
Output :
To put lines into an array :
Output :
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);
?>Code: Select all
Array
(
[0] => 7
3
9
10
4
3
1
8
2
)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);
?>Code: Select all
Array
(
[0] => 7
[1] => 3
[2] => 9
[3] => 10
[4] => 4
[5] => 3
[6] => 1
[7] => 8
[8] => 2
)Code: Select all
$arr = file('array.dat');- dibyendrah
- Forum Contributor
- Posts: 491
- Joined: Wed Oct 19, 2005 5:14 am
- Location: Nepal
- Contact:
This will put everything in a variable, not in array.Mordred wrote:Code: Select all
$arr = file('array.dat');
Oh, really, you have tried it then? (insert orly owl pic heredibyendrah wrote:This will put everything in a variable, not in array.Mordred wrote:Code: Select all
$arr = file('array.dat');
@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');Code: Select all
$arr = file('array.dat');
$arr = array_map('trim', $arr);Code: Select all
$arr = array_map('trim', file('array.dat'));- dibyendrah
- Forum Contributor
- Posts: 491
- Joined: Wed Oct 19, 2005 5:14 am
- Location: Nepal
- Contact:
Sometimes, brain don't work anymore. yes. $arr becomes array after using file() function.Mordred wrote:dibyendrah wrote:This will put everything in a variable, not in array.Mordred wrote:Code: Select all
$arr = file('array.dat');
Oh, really, you have tried it then? (insert orly owl pic here)