View previous topic :: View next topic |
Author |
Message |
canam101 -
Joined: 15 Jan 2007 Posts: 9
|
Posted: Sun Jan 21, 2007 10:25 pm Post subject: Array Problem - disappearing entries |
|
|
I'm hoping this is an obvious beginner's error.
I'm reading in a flat file with three records in it. For each read, I add the record to the array. The keys are 1,2,3.
On the first read the first record is present and viewable via key = 1.
On the second read, the first record has disappeared, but the second record is viewable via key = 2.
On the third read only the third record is present on the array.
I also printed the array after the file is closed, and it shows only the third record as present.
Any ideas? Here's the script:
<?php
$filename = 'tmpmsg.txt';
$i == 0;
$fp = popen("/usr/bin/tail -$limit $filename", 'r');
while (!feof($fp) ) {
$line = fgets($fp);
$i += 1;
$arr = array($i => $line);
print_r($arr);
}
fclose($fp);
print_r($arr);
?> |
|
Back to top |
|
 |
roganty -
Joined: 08 Jun 2004 Posts: 357 Location: Bristol, UK
|
Posted: Sun Jan 21, 2007 11:33 pm Post subject: Re: Array Problem - disappearing entries |
|
|
It is because of the following line.
Code: | $arr = array($i => $line); |
Every time it loops through it is adding the line to the variable, but it is overwriting the old one.
What you need to do is declare an array outside the loop, then add the value to it within the loop
Code: | <?php
$filename = 'tmpmsg.txt';
$i = 0; //double "=="????
$fp = popen("/usr/bin/tail -$limit $filename", 'r'); //the tail command, are you using linux?
//Where is $limit declared?
$arr = array(); //declare array
while (!feof($fp) ) {
$line = fgets($fp);
$i++; //different way of adding one
$arr[$i] = $line; //assign value to array
print_r($arr);
}
fclose($fp);
print_r($arr);
?> |
_________________ Anthony R
Roganty | Links-Links.co.uk |
|
Back to top |
|
 |
canam101 -
Joined: 15 Jan 2007 Posts: 9
|
Posted: Mon Jan 22, 2007 12:34 am Post subject: |
|
|
Thanks very much. Your changed script worked like a charm.
$fp = popen("/usr/bin/tail $filename", 'r'); //the tail command, are you using linux?
//Where is $limit declared?
Yes, linux. I copied that from somewhere, but when I just tried it without the $limit it worked, so the version above should be ok.
$arr[$i] = $line; //assign value to array
Thanks. It even make more intuitive sense than what I was using. |
|
Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|