user1040259
user1040259

Reputation: 6509

How is this associative array foreach working?

I'm perplexed as to how this is not erroring on my server with the highest error reporting to be shown? Any insight is gladly welcomed.

$myArray = ['first' => '1A', 'second' => '2A', 'first' => '2A', 'second' => '2B'];

foreach($myArray as $value) {
    echo $value['first'] . "<br />";
}

Outputted:

1A
2A

Upvotes: 3

Views: 92

Answers (2)

Isaac Hern&#225;ndez
Isaac Hern&#225;ndez

Reputation: 67

First, You have duplicated the Keys in the array and that is not allowed. If you want make the array with the key, you should use something like this:

  foreach (array_expression as $key => $value)

http://php.net/manual/en/control-structures.foreach.php

Upvotes: 1

Ahmed Fathi
Ahmed Fathi

Reputation: 46

You have duplicated array Keys and this is not allowed on arrays Check Arrays

You have to reformat Your array to be like this

$myArray = [['first' => '1A', 'second' => '2A'], ['first' => '2A', 'second' => '2B']];
foreach($myArray as $key => $value) {
    echo $value['first']."<br / >";
}

Upvotes: 3

Related Questions