Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 939
user1040259 Avatar asked Apr 15 '26 06:04

user1040259


1 Answers

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 / >";
}
like image 106
Ahmed Fathi Avatar answered Apr 18 '26 02:04

Ahmed Fathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!