Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Pontus Bolmér
Pontus Bolmér
12,471 Points

Why do you get the key from a foreach loop

It might be a stupid question! But if i have a foreach loop

foreach($list as $key => $item) {
    echo $key . " " .$item["title"] . "</br>";
}

Why do you need to retrive the key value? When you get all u want by simply just writing item[title]

I guess my question is, when do you use the key value?

1 Answer

Maybe, like in your example, you want to echo the key value to make a list.

Another thing you could do is use the key to alter the output. For example, let's say we want the second iteration in the array to have a bold title. Important to note is that in this case example your array keys must be ascending and numeric:

<?php
foreach( $list as $key => $item ) {
    if ( $key == 1 ) {
        echo $key . ' <strong>'.$item['title'].'</strong><br>';
    } else {
       echo $key . ' ' .$item['title'] . '<br>";
    }
}