0

I am trying to loop through an array with duplicate indexes. But it only prints 3 times not all of them. I want to print all values in the array is that possible?

Here is my PHP code:

$data['Video'][0]['name']='a';
$data['Video'][1]['name']='b';
$data['Video'][1]['name']='c';
$data['Video'][3]['name']='d';
$data['Video'][3]['name']='e';

foreach ($data['Video'] as $video) {
    print_r($video);
}

And here is the output of that code:

Array
(
    [name] => a
)
Array
(
    [name] => c
)
Array
(
    [name] => e
)
2
  • You are changing the value of array index 3 and 1 two times. So in total there are only 3 arrays in $data['Video'] Commented Dec 25, 2013 at 6:21
  • it will overwrite the value at that index... Commented Dec 25, 2013 at 6:25

2 Answers 2

1

Well, the duplicate indexes negate each other. So this is expected behavior. So when you set this in your code:

$data['Video'][0]['name']='a';
$data['Video'][1]['name']='b';
$data['Video'][1]['name']='c';
$data['Video'][3]['name']='d';
$data['Video'][3]['name']='e';

It really just means this:

$data['Video'][0]['name']='a';
$data['Video'][1]['name']='c';
$data['Video'][3]['name']='e';

The newer data assigned to the keys 1 and 3 overwrite what was previously there.

Sign up to request clarification or add additional context in comments.

1 Comment

nice explainment +1 but they dont "negate" in mine opinion an better definition would be "overwrite" or "override"
0

Please avoid duplicate entry of keys otherwise try this,

  $data['Video'][]['name']='a';
  $data['Video'][]['name']='b';
  $data['Video'][]['name']='c';
  $data['Video'][]['name']='d';
  $data['Video'][]['name']='e';

  foreach ($data['Video'] as $video) {
      print_r($video);
  }

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.