0

I have set up a multidimensional array in PHP like this:

$contents = array(
    "Header1" => array(
         "Section 1" => array (
               "Description1",
               "Notes1",
         ),
         "Gap" => "Gap",
         "Section 2" => array (
               "Description2",
               "Notes2",
         ),
         "Gap" => "Gap",
         "Section 3" => array (
               "Description3",
               "Notes3",
         ),
    ),
);

then I loop through this array as follows:

foreach ($contents as $header => $section) {
      foreach ($section as $title => $details) {
            echo $title."<br>";
      }
}

The output will be:

Section1
Gap
Section2
Section3

Why isn't the second "Gap" showing?

Thanx

1

2 Answers 2

5

Because you can't have duplicate array keys. The second one overwrites the first.

Use Gap2 or something for your next array key. Or, better yet, nest it:

array(
    'Gap' => array(
        'Gap1',
        'Gap2'
    )
);
Sign up to request clarification or add additional context in comments.

4 Comments

The first one overwrites the second one :)
@Akam Hash-maps (also known as associative arrays in PHP) don't guarantee order. See this phpfiddle.org/main/code/k04-p2i. The second value takes precedence, whether or not it shows up in the place of the first. Curious why you posted a code sample after I clearly posted one that indicated you weren't going to win this ;).
we are not competitor to win or loss. it's a matter to learn, correct and incorrect :)
Ok thanks, this is indeed a very stupid mistake :). Well, I won't make it again, that's what matters...
3

You cannot have two values in your array bind to the same key. A common method is to put your multiple values inside another sub-array, but while using the same key. It adds complexity to your code though. Careful.

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.