Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
)
share|improve this question
    
You are changing the value of array index 3 and 1 two times. So in total there are only 3 arrays in $data['Video'] –  Subin Dec 25 '13 at 6:21
    
it will overwrite the value at that index... –  Pranav C Balan Dec 25 '13 at 6:25
add comment

2 Answers

up vote 0 down vote accepted

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);
  }
share|improve this answer
    
It solved my problem. thanks –  Abhijeet Kambli Dec 25 '13 at 6:30
add comment

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.

share|improve this answer
    
nice explainment +1 but they dont "negate" in mine opinion an better definition would be "overwrite" or "override" –  Raymond Nijland Dec 25 '13 at 16:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.