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

How does the each function in PHP work?

From what I understand, the each() function loops through an array and stores the key/value pairs.

in the example used in this example, she then stores the values in the list() function

<?php
while(list($key, $val) = each($array)) {
  "$key => $val\n";
}
?>

so does the list() function take the key/value from the each($array) then store them in the parameters held inside list($key, $val). From there, you can use the parameters in the code block?

Side question: Is the reason you would include the list() function is so that you can use the parameters? is that the only benefit?

Thanks

1 Answer

Daniel Box
Daniel Box
1,939 Points

so does the list() function take the key/value from the each($array) then store them in the parameters held inside list($key, $val). From there, you can use the parameters in the code block?

  • Yes. each() will return the current key and value only and list() allows you to assign those values to a list of variables. each() also moves you onto the next record of the array (advances the array cursor) so on the next iteration of the loop you'll get the new values in to the list variables.

As for your side question, it seems using using a foreach loop is faster and cleaner

See: http://php.net/manual/en/function.each.php

Also found this which states that while list each could be useful for when you want to alter the array in the while block: http://stackoverflow.com/questions/3304885/whilelistkey-value-eacharray-vs-foreacharray-as-key-value

Hey, Daniel, thank you for the reply, and the additional info!