Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

using foreach to loop through an array in the php Array's and Datastructures Course

Hello, Ive just been stumped on something that seems relatively trivial.

here is my code

$list[] = array(
    'title' => 'Laundry',
    'priority' => 2,
    'due' => '06/09/2016',
    'day' => 0,
    'repeat' => true,
    'complete' => false,
);
$list[] = array(
    'title' => 'Dishes',
    'priority' => 2,
    'due' => null,
    'day' => 0,
    'repeat' => true,
    'complete' => false,
);
$list[] = array(
    'title' => 'Dust',
    'priority' => 3,
    'due' => null,
    'day' => 5,
    'repeat' => true,
    'complete' => false,
);




$newArray = array ('one' => '1', 'two' => '2', 'three' => '3');

foreach ($newArray as $key => $value) {
    echo $key . " = " . $value . "\n";
}

foreach ($list as $key => $item) {
    echo $key . '=' . $item;
}

The first hash works as expected, but I am getting a string conversion error looping through the $list hash, when Im expecting the same result. $list[] is an example of the multidimensional array Im working with.

Thanks for help, Chris

1 Answer

Dee Barizo
Dee Barizo
8,402 Points

$item is an array. For example, this is $item when the loop runs for the first time:

Array ( [title] => Laundry [priority] => 2 [due] => 06/09/2016 [day] => 0 [repeat] => 1 [complete] => )

To use the echo function, you need a string, which is why you get an error because $item is not a string but an array.