Nicolas Widart
Nicolas Widart

Reputation: 1287

Laravel: Undefined index - array key not existant

I've been looking into this problem for a couple of days now and I just can't seem to figure it out.

I'm trying to do something simple, I thought, just looping through an array. This is a screenshot of the array: http://cl.ly/image/3j2J3x1C3B0j I'm trying to loop through all the 'Skills' array, there the "Skill' array and inside that grabbing the "Icon". For this I made 2 loops:

    foreach ($hero_data['skills'] as $skills)
            {
                foreach ($skills as $skill)
            {
                //print_r($skill['skill']);
            }
    }

Unfortunaly this doesn't work, in laravel. I'm getting the "Undefined index: skill" error. It does work when I tried it outside , as a standalone script.

Out side both of the loops I can select the icon with:

    print_r($hero_data['skills']['active'][0]['skill']['icon']);

I'm sure I'm overlooking something stupid...

Thanks a lot for the help,

Upvotes: 1

Views: 32840

Answers (4)

BadHorsie
BadHorsie

Reputation: 14544

Looking at what you've said from the other solutions posted here, it's clear that you are looping through the sub arrays and not all of those sub arrays contain the keys that your further loops are looking for.

Try this:

foreach ($hero_data['skills']['active'] as $skills) {
    if (isset($skills['skill']['icon'])) {
        print_r($skills['skill']['icon']);
    }
}

Because, for example, if $hero_data['skills']['active'][8] doesn't actually have a skill array or a ['skill']['icon'] array further down, then the loop will throw the errors you have been reporting.

The nested array keys you are looking for must be found in every iteration of the loop without fail, or you have to insert a clause to skip those array elements if they aren't found. And it seems like your $hero_data array has parts where there is no ['skill'] or ['icon'], so therefore try inserting one or more isset() checks in the loops. Otherwise, you need to find a way of guaranteeing the integrity of your $hero_data array.

Your game looks interesting by the way!

Upvotes: 2

Menthas
Menthas

Reputation: 26

You simply need to iterate the active index of the array. this should work :

foreach ($hero_data['skills']['active'] as $skills) {
    print_r($skills['skill']['icon']);
}

Upvotes: 0

Brian
Brian

Reputation: 8616

Try:

foreach ($hero_data['skills'] as $skills)
{
  foreach ($skills as $skillState)
  {
    foreach ($skillState as $skill)
    {
      print_r($skill['skill']);
    }
  }
}

Upvotes: 0

Tomer
Tomer

Reputation: 17930

Inside skills you have an 'active' attribute and it contains the array you need, so you need to change your code to this:

 foreach ($hero_data['skills'] as $skills)
            {
                foreach ($skills['active'] as $skill)
            {
                //print_r($skill['skill']);
            }
    }

Upvotes: 0

Related Questions