PHP foreach prints only some of the items, not all

general-dev

#1

I'm a fresh beginner in PHP and I don't know why my foreach prints only the first and last values, but not the middle one. Please review this code:

<?php

$items = array(
    'item1' => 'X',
    'item2' => 'Y',
    'item2' => 'Z',
);

foreach ($items as $item) {
	echo $item . '<br>';
}

I've tested that code in phptester.net and got:

X

Z

Instead of the expected:

X

Y

Z

Why is that?

Thanks in advance,


#2

I do not know if it makes a difference but you have an extra , at the end of your array.

Also you have a multi dimension array. This works as expected:

<?php

$items = array('X', 'Y', 'Z');

foreach ($items as $item) {
	echo $item . '<br>';
}
?>

#3

You have duplicate keys. item2 appears twice in the array.


#4

Thanks, I will review the keys next time in a similar case.


#5

This is because your $items array is an associative array, you should try something like this

 foreach ($items as $item => $val) {
 	echo $item . '<br>';
 }

this would print only key

item1
item2
item3


#6

There is no such key as item3 in the array posted. There are only two unique keys in the array. Your code would actually print:-

item1
item2

It is the naming of the keys which needs to be corrected.


#7

Just so you know, it doesnt.

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.
http://php.net/manual/en/function.array.php


#8

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.