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,052 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.