简体   繁体   中英

PHP foreach echos a specific array item twice

I take a PHP basics course in teamtreehouse.com and in this course I learn about PHP loops. Regarding PHP foreach loop, I wrote this code which works fine:

<?php

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

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

X

Y

And yet, when I try to target a specific item after iterating foreach element this way:

foreach ($items as $item) {
    echo $items['item1'];
}

The output is XX instead just X .

My question is why I got XX in the first place and an answer could help me understand how to extract the specific value I want (the value of the first key-value pair - X ) with foreach .

There are 2 different things happening:

  • printing the current value from the array for each iteration
  • printing referring to the same item by key for each iteration

This array has 2 items:

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

Now if you loop the array using a foreach , you can use your syntax like:

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

Now you are using $item , which is the current item in the foreach. In this case, this will print 2 different values for each iteration: "X" and "Y".

Now looking at the second part of your code:

foreach ($items as $item) {
    echo $items['item1'];
}

Now you are using $items['item1']; for each iteration. That means that you are referring to the item in $items with the key item1 which has the value of "X". That is why you are getting "X" and "X".

If you direclty want to get an item from the $items , you can do that like this:

$items["item1"];

If you want to use a foreach to get the item where the value is "X", and you know that the key is "item1", you could for example do it like this:

foreach ($items as $key => $item) {
    if ($key === "item1") {
        echo $item;
    }
}

You should know another usecase of foreach:

Foreach will loop every element in array, as well as every {key & value} element.

You can use following code:

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

foreach ($items as $key => $value) {
    echo $key. ":" . $value . "<br>";
}

This will print

item1:X

item2:Y

For each item, as there is two item in the object(the loop is running two times), you're echoing the first item. That's why its showing "xx".

The foreach function iterates through an array as many times as the number of elements in array, which are 2 (first element is with key item1 and second element with key item2 ) here in your example.

The code to access first element in your array is $items['item1']; which upon print/echo will output the value at this key ( item1 ) which is X

Since the foreach function iterated twice, so it executed the code inside it twice as well, which in your case was printing a value X (hence printing two times at the end of iteration)

Just to extract the particular value you can use echo $items['item1'] ; (extracting value at item1 , for example) without foreach loop (since you donot require going through every element here in your array)

for instance, you can try the following code:

<?php

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

echo $items['item1'];

which will have the following output

x

You will need to use foreach only in case when you need to go through all your array to execute some functionality, for accessing a specific element or even for just searching you don't need to use foreach as there are many better functions for arrays in php.

Here's why I got XX from my code.

<?php

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

foreach ($items as $item) {
    echo $items['item1'];
}

With the expression echo $items['item1']; I dictated the loop to negate 'item2' . Thus, it treats only to data in the index of 'item1' , but given the echo is for both the first value of $items and ['item1'] itself, the value is printed twice: Once as a variable expansion of the first value of $items , and second, as from expanding its first value itself with ['item1'] .

This is just how the foreach function of PHP is built.

To affirm this philosophy I did:

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

foreach ($items as $item) {
    echo $items['item1'];   
}

And got: XXX .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM