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 PHP Arrays and Control Structures PHP Loops While Listing Array Values

each() has been deprecated

The PHP Manual says that the each() function has been deprecated as of PHP 7.2.0. Are there any alternative functions that we should use instead?

3 Answers

Benjamin Larson
Benjamin Larson
34,055 Points

Nice catch on actually reading the documentation :)

You'll most often see the foreach loop used instead of the while / each syntax. There are probably others ways to accomplish it, but that's the most common alternative (although it's been more the standard practice than the alternative). Alena will introduce the for loops in the coming lessons.

Great, thanks!

Quick foreach example for anyone interested:

$arr = array('lol', 'smh', 'yolo', 'wtf');

foreach ($arr as $k => $v) {
  echo '<p>The key is ' . $k . ' and its value is ' . $v . '</p>';
}

thanks eric!

I noticed that too. In the tut she checks two conditions. while (list($key, $val) = each($fruit) && ($count++ < 2))

I tried a foreach with the second condition... Would this be correct, or is there another way that is more accepted/standardized? Is this the right place to ask, I feel like it would be since op was pointing out that each is deprecated...

$fruits = ['a' => 'apple', 'b' => 'banana', 'c' => 'cranberry']; $i = 0; foreach ($fruits as $key => $value) { if ($i++ >= 2) break; $value.= "s"." are yummy.\n"; echo $key.": ".$value; }; //a: apples are yummy. //b: bananas are yummy.