Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Error: Undefined offset: 1

Tags:

php

undefined

It seems like this might be an error dealing with arrays, but I can't figure it out. I'm really just starting with PHP and this is getting to be a little intimidating. Any help would be greatly appreciated! here is my code:

<?php echo "<h1>Choose a Poll!</h1>";

$read = file('poll_topics.txt');   
$data = array( );           
foreach($read as $lines){           
    list($key,$v) = explode("|","$lines");          
    $data[$key] = $v;
}

foreach ($data as $k=>$desc){               
    echo "<ul><li><a href='take_a_poll.php?poll=$k'>$k</a> - $desc </li></ul>";
}

?>

Here is what is in the text file:

  Instruments|What kind of instruments do you like?
  Music|What type of music do you like best?

I should clarify: The error is line 20, or where it says list($key,$v) = explode...

like image 696
eightonrose Avatar asked Feb 25 '23 17:02

eightonrose


1 Answers

You have an empty line somewhere. That's why explode() will return only an empty $key, but have nothing to assign to the $v. And that's when it prints that notice.

You can rewrite it a bit to ignore such cases:

foreach ($read as $lines) {
    $key = strtok($lines, "|");
    $v = strtok("|");
    if ($v) {
        $data[$key] = $v;
    }
}

This will also avoid an empty entry in your final $data array.

like image 122
mario Avatar answered Mar 08 '23 08:03

mario