Re: Undefined offset notice with explode





Jerry Stuckle wrote:
> Richard Lawrence wrote:
> > Hi there,
> >
> > I'm having a problem with PHP which I'm not sure how to best solve.
> > Here is the code:
> >
> > $fp = fopen("comments.txt", "r");
> > while(!feof($fp))
> > {
> > $line = fgets($fp, 1024);
> > list($key, $value) = explode(":", $line, 2);
> >
> > if ($key == "something")
> > {
> > ...etc...etc...
> >
> > The problem here is that if the line doesn't contain a : then there
> > isn't anything to populate $key and $value and so PHP reports "PHP
> > Notice: Undefined offset: 1". When I used to work with Perl, it
> > wouldn't report and rely on me handling the issue later if needs be.
> >
> > What is the best way to get the explode line to not report a PHP notice
> > when it comes across a $line that isn't in the correct format?
> >
> > Many thanks,
> >
> > Richard.
> >
>
> if (strpos($line, ':') !== false)
> list($key, $value) = explode(":", $line, 2);
> else
> whatever...


if (strpos(trim($line),':') === false) $line = trim($line) . ':'; //
add a colon to the line if one isn't there after trimming off the
trailing CR/LF

Ken

.



Relevant Pages

  • Re: Novice looking for advice (date comparison).
    ... (It would also be nice to include day-names on the report.) ... In PHP, loop through the range of dates. ... Jerry Stuckle ... JDS Computer Training Corp. ...
    (comp.lang.php)
  • Re: Why wont this work
    ... I have inherited a web site written in PHP. ... so I have added this new report to the bottom of a pull down ... Jerry Stuckle ... Visual Studio to debug code line by line to see where errors occur, ...
    (comp.lang.php)
  • Re: Why wont this work
    ... I have inherited a web site written in PHP. ... so I have added this new report to the bottom of a pull down ... Jerry Stuckle ... JDS Computer Training Corp. ...
    (comp.lang.php)
  • Re: Undefined offset notice with explode
    ... Richard Lawrence wrote: ... I'm having a problem with PHP which I'm not sure how to best solve. ... What is the best way to get the explode line to not report a PHP notice ...
    (comp.lang.php)
  • Stuck & Need Help with "Generate Report"
    ... I need to complete this "Generate Report" page for my employer and I'm ... What I want to do is create a single file to display and process the ... can I have this page split PHP | HTML |PHP when using the "if ... php file so that if sumbitted, here is the query and output BUT if not ...
    (comp.lang.php)