note 88578 modified in control-structures.foreach by danbrown

From: Date: Fri, 30 Jan 2009 14:54:33 +0000
Subject: note 88578 modified in control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-149976@lists.php.net to get a copy of this message
foreach and the while/list/each methods are not completely identical, and there are occasions where one way is beneficial over the other. <?php $arr = array(1,2,3,4,5,6,7,8,9); foreach($arr as $key=>$value) { unset($arr[$key + 1]); echo $value . PHP_EOL; } ?> Output: 1 2 3 4 5 6 7 8 9 <?php $arr = array(1,2,3,4,5,6,7,8,9); while (list($key, $value) = each($arr)) { unset($arr[$key + 1]); echo $value . PHP_EOL; } ?> Output: 1 3 5 7 9 [EDIT BY danbrown AT php DOT net: Contains a typofix by (scissor AT phplabs DOT pl) on 30-JAN-2009.] --was-- foreach and the while/list/each methods are not completely identical, and there are occasions where one way is beneficial over the other. <?php $arr = array(1,2,3,4,5,6,7,8,9); while (list($key, $value) = each($arr)) { unset($arr[$key + 1]); echo $value . PHP_EOL; } ?> Output: 1 2 3 4 5 6 7 8 9 <?php $arr = array(1,2,3,4,5,6,7,8,9); while (list($key, $value) = each($arr)) { unset($arr[$key + 1]); echo $value . PHP_EOL; } ?> Output: 1 3 5 7 9 http://php.net/manual/en/control-structures.foreach.php

« previous php.notes (#149976) next »