I get undefined index when I try to access to a nested array but the key actually exist [PHP]

I have this array and I want to access to [“question”] array with a foreach loop but when I try to access it says that im trying to access to undefined index but the index question alredy exists.

My array

array(2) {
  ["question_9"]=>
  array(1) {
    ["question"]=>
    string(5) "Do you like cake?"
  }
  ["options"]=>
  array(3) {
    ["option_26"]=>
    string(20) "Yes"
    ["option_25"]=>
    string(19) "No"
    ["option_24"]=>
    string(13) "Maybe"
  }
}

this is my code :

foreach ($questionsArray as $question) {
  echo "Question.".$question["question"];
}

How I can access to this value? :frowning:

If this is your $questionArray

array(2) {
  ["question_9"]=>
  array(1) {
    ["question"]=>
    string(5) "Do you like cake?"
  }
  ["options"]=>
  array(3) {
    ["option_26"]=>
    string(20) "Yes"
    ["option_25"]=>
    string(19) "No"
    ["option_24"]=>
    string(13) "Maybe"
  }
}

Then you first need to get past the question_9 piece. The structure is less than friendly.

Well, this array is badly formed. It can be read using the correct code, but, the logic of the array does not make much sense. If you have a large base of questions and options, you would have two arrays, one with all of the options and one with the questions and a list of the options for that question. Hard to guess as it depends on your needs for the data.

But, to explain the “foreach” a little, you can get one item at a time from it. In this case it grabs the Question_9 array and then follows it with the Options array. Therefore you would get “ARRAYS” out of it, not data. You can do it in a different way that would get the key and data separately, loosely like this:

foreach ($questionsArray as $key=>$question) {

This would give you the key and the array beyond it. But, you would need to then parse the $question which would also be an array. Since each of the items in the $questionArray have different layouts, you would need to parse them differently. You could possibly use nested foreach functions and pull out the final data, loosely like this:

foreach ($questionsArray as $key=>$question) {
    foreach($question as $key2=>$data) {
         //  Do something with the list of data based on the $key and $key2 values
   }
}

Again, all this depends on what you are really attempting to do. Where does the data come from? Why is it in this badly formed array structure? Lots of questions. Perhaps more info would help us help you.

Sponsor our Newsletter | Privacy Policy | Terms of Service