Re: string concatenation with fgets
| From: | Ashley Sheridan | Date: | Mon, 30 Nov 2009 17:42:42 +0000 |
| Subject: | Re: string concatenation with fgets | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-300164@lists.php.net to get a copy of this message | ||
On Mon, 2009-11-30 at 09:40 -0800, aurfalien@gmail.com wrote:
> Hi Ash,
>
> Actually I need the if because the code will print out an empty line
> and add "sometext" to it.
>
> So without the if check for an empty line, at the end of the loop I'll
> get sometext. For example, if the file I am processing called
> somename.txt has
>
> a
> b
> c
>
> in it. I'll have;
>
> asometext
> bsometext
> csometext
>
> but w/o the if check, I'll also have
>
> sometext
>
> as well.
>
>
>
> On Nov 30, 2009, at 9:24 AM, Ashley Sheridan wrote:
>
> > On Mon, 2009-11-30 at 09:04 -0800, aurfalien@gmail.com wrote:
> >>
> >> Hi Shawn,
> >>
> >> Your code looks cleaner then mine so i tried it and got the last
> >> entry
> >> in the txt file printed twice.
> >>
> >>
> >> On Nov 30, 2009, at 7:07 AM, Shawn McKenzie wrote:
> >>
> >> > aurfalien@gmail.com wrote:
> >> >> So here is my final test code, notice the check for ' ' in the if.
> >> >>
> >> >> Since I'm on Linux, this has to do with whats between the last
> >> LF and
> >> >> EOF which is nothing but this nothing will get printed out.
> >> >>
> >> >> $file = fopen("somefile.txt", "r");
> >> >> while (! feof($file))
> >> >> {
> >> > $tmp = trim(fgets($file));
> >> > if ($tmp != '')
> >> >> {
> >> > $names = $tmp;
> >> >> }
> >> >> print $names."sometext\n";
> >> >> }
> >> >> fclose($file);
> >> >>
> >> >>
> >> >
> >> > --
> >> > Thanks!
> >> > -Shawn
> >> > http://www.spidean.com
> >>
> >>
> >
> > Remove the if statement and just print out $tmp. The while loop is
> > going over one extra time than you need, and on that final
> > iteration, $tmp is an empty string. The if statement only changes
> > $name if $tmp is empty, so it leaves it as it was, hence you getting
> > the last line printed twice. Printing out an empty string in this
> > example won't do anything, and the if statement is also pretty
> > useless as it just copies the value to another variable on a
> > condition that will only result in the side-effect you've noticed.
> >
> > Thanks,
> > Ash
> > http://www.ashleysheridan.co.uk
> >
> >
>
Then put the print statement inside the if, not the assignation,
otherwise you will always get that last line!
Thanks,
Ash
http://www.ashleysheridan.co.uk