note 18021 added to control-structures.foreach

From: Date: Mon, 07 Jan 2002 20:29:02 +0000
Subject: note 18021 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-24508@lists.php.net to get a copy of this message
There was discussion at earlier about the inability to nest foreach loops on the same array. The most efficient solution that I have found is this: $keys=array_keys($array); for ($i1=0; $i1<count($array); $i1++) for ($i2=0; $i2<count($array); $i2++) ...and so on... Then you just reference $array[$keys[$i1]], $array[$keys[$i2]], and so on for the respective loop variables. Their keys are, of course, $keys[i1], $keys[i2], and so on. The main benefit of this method over the other is that you don't need a new array for a new layer of nesting. There are two caviats to this method, however. First, you are dealing with the actual array values, not copies of them like the foreach statement gives you. This is usually a benefit rather than a drawback. Second, if you add any new array indices in the process of looping, those new indices will not be processed, because their keys will not be in the keys table. But again, this is not usually an issue. -- http://www.php.net/manual/en/control-structures.foreach.php http://master.php.net/manage/user-notes.php?action=edit+18021 http://master.php.net/manage/user-notes.php?action=delete+18021 http://master.php.net/manage/user-notes.php?action=reject+18021

« previous php.notes (#24508) next »