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

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.