King of Arrays | Error


Hello all!

Could someone please assist me with this snippet of code? I can't seem to find the error. The window shows this:

Undefined index: charcoal (line 16)Would you like to purchase Undefined offset: 0 (line 20)Undefined offset: 1 (line 20)Undefined offset: 2 (line 20)Undefined offset: 3 (line 20)Spatula

However, It says "congratulations" and gives me the green light to move forward. If I am missing something could someone please point it out?

Thank you.

    <title>I am the King of Arrays!</title>
      // On the line below, create your own associative array:
       $myArray = array('item1' => 'Grill',
                     'item2' => 'Spatula',
                     'item3' => 'charcoal',
                     'item4' => 'tarp');

        $length = count($myArray);
      // On the line below, output one of the values to the page:
     echo 'Would you like to purchase ' . ' ' . $myArray['item2'];
      // On the line below, loop through the array and output
      for ($i = 0; $i < $length; $i++) { 
        echo $myArray[$i];    
      // *all* of the values to the page:
     echo $myArray['item2'];


Hi @apprentice20190,

Look at where you defined your array. The keys to the array are item1, item2, etc. This is an associative array that we are working with.

Now look at your for loop. There, you are trying to use integers as keys to access the values in your array. This is why you are seeing an undefined offset error message.

Have a look back at exercise 5, that is where we were shown how to use a foreach loop to loop through associative arrays.


Thanks for your help, I can't believe I fell into that trap. I was looking at that for hours trying to figure it out, and it was right in front of me the whole time.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.