PHP error: Undefined offset: 1

It seems like it might be an error related to arrays, but I can't figure it out. I really start with PHP and it gets 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 have to clarify: The error is line 20 or where list($key,$v) = explode...

+4
source share
3 answers

You have an empty string somewhere. Therefore, explode() returns only the empty key $, but does not have the right to assign the value $ v. And that is when it prints this 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.

+4
source

Try the following:

 <?php echo "<h1>Choose a Poll!</h1>"; $_fileData = file_get_contents('poll_topics.txt'); $_results = array(); if ( ! empty( $_fileData ) ) { foreach ( $_fileData as $_line ) { $_split = explode( '|', $_line ); // Many ways to do this: // if ( !empty( $_split ) && 2 == count( $_split ) ) then no error else error // or... if ( isset( $_split[0], $_split[1] ) ) { $_key = $_split[0]; $_value = $_split[1]; if ( null !== $_key && null !== $_value ) { $_results[ $_key ] = $_value; // or $_results[] = array( $_key => $_value ); if key can be duplicated } } } } 
+2
source

You can try using the array_pad() function. Use it where you wrote the break function.

 $_split = array_pad(explode( '|', $_line ), numberOfElementsInArray, null); 
0
source

Source: https://habr.com/ru/post/1344864/


All Articles