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 Integrating PHP with Databases Using Relational Tables Fetching in a While Loop

How does this code ' $item[$row["role"]][] = $row["fullname"]' know how to allocate 'fullName' to the correct key

I'm confused as to how the code ' $item[$row["role"]][] = $row["fullname"]' knows how to allocate 'fullName' to a pre existing role key.

The video explains that the while loop code 'while( $row = $result->fetch(PDO::FETCH_ASSOC)) pulls the row data one at a time like this $row: 'actor', 'John Livingston'.

How does ' $item[$row["role"]][] = $row["fullname"]' know how to add (using the Ron example above) 'Ron Livingston as a value' to 'actor' in a situation, for example where the actor key has already been added by to the array by the while loop from a previous row where the key is also actor? How does the code know how to sort the code in this way rather just creating a second actor key and adding Ron Livingston to that?

1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there, Matt Nickolls! When it does $item[$row["role]][] it is creating an associative array such that the "key" is the the role, and the value is yet another array. If the key didn't exist before when we get to the person, it will create that key. When it gets to another person with the same role, it adds that person to the array stored at the same key. For example, if you take a look at "Much Ado About Nothing" and var_dump($item) after the loop and before you return it you will see this for the "star" key.

["star"]=> array(3) { [0]=> string(15) "Kenneth Branagh" [1]=> string(13) "Emma Thompson" [2]=> string(12) "Keanu Reeves" } }

Which means that you have something like this if you were hard-coding it yourself:

$stars = array("star" => ["Kenneth Branagh", "Emma Thompson", "Keanu Reeves"]);

Hope this helps! :sparkles: