Tuesday, March 3, 2009

Reading a text file into an array PHP

Simply write to code as below to read the text file into an array.

Create a PHP file called file.php inside the filesystem folder. Insert the following
code, Before we start coding we need to know is "Text files can be used as a flat-file database—where each record is stored on a separate line, with a tab, comma, or other delimiter between each field"


<?php
// read the file into an array called $users
$users = file('C:/private/filetest03.txt');
?>
<pre>
<?php print_r($users); ?>
</pre>

This draws the contents of filetest03.txt into an array called $users, and then
passes it to print_r() to display the contents of the array. The <pre> tags simply
make the output easier to read in a browser.

Or you can write as following if you have more data seperated by "," operator

<?php
// read the file into an array called $users
$users = file('C:/private/filetest03.txt');
// loop through the array to process each line
for ($i = 0; $i < count($users); $i++) {
// separate each element and store in a temporary array
$tmp = explode(', ', $users[$i]);
// assign each element of the temporary array to a named array key
$users[$i] = array('name' => $tmp[0], 'password' => $tmp[1]);
}
?>
<pre>
<?php print_r($users); ?>
</pre>

Here the above code means, The count() function returns the length of an array, so in this case the value of count($users) is 2. This means the first line of the loop is equivalent to this:

for ($i = 0; $i < 2; $i++) {

The loop continues running while $i is less than 2. Since arrays are always counted
from 0, this means the loop runs twice before stopping.

Inside the loop, the current array element ($users[$i]) is passed to the explode()
function, which converts a string into an array by splitting the string each time it
encounters a separator. In this case, the separator is defined as a comma followed
by a space (', '). However, you can use any character or sequence of characters:
using "\t" as the first argument to explode() turns a tab-separated string into an array.

The first line in filetest03.txt looks like this for example:
james, jamespassword

When this line is passed to explode(), the result is saved in $tmp, so $tmp[0] is
david, and $tmp[1] is codeslave. The final line inside the loop reassigns $tmp[0] to
$users[0]['name'], and $tmp[1] to $users[0]['password'].

The next time the loop runs, $tmp is reused, and $users[1]['name'] becomes
gayle, and $users[0]['password'] becomes gaylepassword.

Output will be :

Array{
[0] => Array
{
[name] => james
[password] => jamespassword
}
[1] => Array
{
[name] => gayle
[password] => gaylepassword
}
}

In one word you can write as

$users[$i] = array('name' => $tmp[0], 'password' => rtrim($tmp[1]));

0 comments:

Post a Comment