-2

This is my code:

$recommendations_name_list = explode(',',$result[$x]["recommendations_title"]);
$recommendations_vote_average = explode(',',$result[$x]["recommendations_vote_average"]);


foreach( $recommendations_name_list as $index => $recommendations_title ) {
           echo'<p>'.$recommendations_title.'</p>
                <p>'.$recommendations_vote_average[$index].'</p>';
}

Now, If in the 9th loop$recommendations_title have some value but $recommendations_vote_average[$index] do not have a value. Then I get this error:

Notice: Undefined offset: 9

Josh Poor
  • 505
  • 1
  • 5
  • 12
  • it just says that your second variable is not as long as your first variable (the one you used for the foreach) – Edwin Jun 29 '17 at 14:34
  • check the value or array is set – san san Jun 29 '17 at 14:35
  • Hey Josh, haven't read your question yet, but I already want to point out that your question's title is pretty bad. What to do if there is a variable inside a foreach loop? It really doesn't say anything. – domsson Jun 29 '17 at 14:36
  • Check your array with `var_dump($recommendations_name_list); var_dump($recommendations_vote_average)` – Richard Jun 29 '17 at 14:37

1 Answers1

1

You need to check if that key isset in your second array before echo it because you can't echo a value that is not set.

$recommendations_name_list = explode(',',$result[$x]["recommendations_title"]);
$recommendations_vote_average = explode(',',$result[$x]["recommendations_vote_average"]);


foreach( $recommendations_name_list as $index => $recommendations_title ) {
    echo'<p>'.$recommendations_title.'</p>';

    if(isset($recommendations_vote_average[$index])){

        echo '<p>'.$recommendations_vote_average[$index].'</p>';
    }else{
        echo '<p>No value</p>';
    }
}
Edison Biba
  • 4,384
  • 3
  • 17
  • 33