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 Integrating PHP with Databases Querying the Database with PHP Working with Results

I don't understand why this foreach loop doesn't loop through a multi-dimensional array

When I use

$results_array = $results->fetchAll(PDO::FETCH_ASSOC);

foreach($results_array as $key => $value) {
    send_offer($key["member_id"], $key["email"], $key["fullname"], $key["level"]);
}

The code doesn't pass the challenge. By when I replace $key => $value with just $key it passes. This is majorly confusing to me because the results of a database query is a multi-dimensional array and in order to loop through a multi-dimensional array you need a $key and a $value. I'm at a complete loss.

index.php
<?php
include "helper.php";

try {
    $results = $db->query(
        "SELECT member_id, email, fullname, level FROM members"
    );
} catch (Exception $e) {
    echo $e->getMessage();
}
//add code below this line
$results_array = $results->fetchAll(PDO::FETCH_ASSOC);

foreach($results_array as $key => $value) {
    send_offer($key["member_id"], $key["email"], $key["fullname"], $key["level"]);
}

1 Answer

Pascal Boschma
Pascal Boschma
379 Points

A multi-dimensional array is an array existing out of other arrays. This is not what you are doing here.

foreach($results_array as $value) loops over the array given to him by $results_array. On each iteration, the current value will be asigned to the variable $value.

foreach($results_array as $key => $value) will assign the key to the first variable, $key (as an addition).

Even without the key variable, you can call it by your key, as this is your key. (I know, I know)