0

I have this following array

$question = array(
    "ques_15" => array(
        "name" => array(
            "0" => "aaa"
        )
    ),
    "ques_16" => array(
        "name" => array(
            "0" => "bbb",
            "1" => "ccc"
        )
    )
);
$i=0;
foreach($question as $k=>$v)
{
   echo $question[$k]['name'][$i];
    $i++;
}

But my output is only

aaaccc

I am missing the value bbb

1
  • 1
    $i is going 0,1,2 etc, but you have two "0" in your array. Commented Jul 16, 2014 at 16:22

4 Answers 4

2

You need to iterate the inner 'name' arrays - you could use a nested foreach loop:

$question = array(
    "ques_15" => array(
        "name" => array(
            "0" => "aaa"
        )
    ),
    "ques_16" => array(
        "name" => array(
            "0" => "bbb",
            "1" => "ccc"
        )
    )
);
foreach($question as $quest)
{
   foreach($quest['name'] as $val)
   {
       echo $val;
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot.Working great also understood the iteration now.
1

you should loop though like so

foreach($question as $q)
{
   foreach($q['name'] as $v)
   {
       echo $v;
   }
}

Comments

1

in foreach you don't need a counter $i, it's for while() or for()

you array is two dimensional so you need 2 foreach

Comments

1

Check it out in a functional way.
The shorthand array declaration works only on PHP 5.4+ though, but it still works with your longhand array declaration.

$questions = [
    'ques_15' => ['name' => ['aaa']],
    'ques_16' => ['name' => ['bbb', 'ccc']]
];

array_map(function($a){
    foreach ($a['name'] as $v) echo $v;
}, $questions);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.