note 52892 modified in control-structures.foreach by danbrown
| From: | danbrown@php.net | Date: | Tue, 28 Apr 2009 13:10:25 +0000 |
| Subject: | note 52892 modified in control-structures.foreach by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-153923@lists.php.net to get a copy of this message | ||
I had the same problem with foreach() and a recursiv function. If you don't want to spend about
1 or 2 hours to solve this problem, just use for() loops instead of foreach().
Some Example:
<?php
$arr[] = array(1,"item1");
$arr[] = array(2,"item2");
$arr[] = array(1,"item3");
//$arr[] = ...
//doesn't work
function foo($x) {
global $arr; // some Array
foreach($arr as $value) {
if($value[0] == $x) {
echo $value[1]."\n";
foo($value[0]);
}
}
}
//just use this
function foo($x) {
global $arr; // some Array
for($i=0; $i < count($arr); $i++) {
if($arr[$i][0] == $x) {
echo $arr[$i][1]."\n";
foo($arr[$i][0]);
}
}
}
?>
Paul
--was--
I had the same problem with foreach() and a recursiv function. If you don't want to spend about
1 or 2 hours to solve this problem, just use for() loops instead of foreach().
Some Example:
$arr[] = array(1,"item1");
$arr[] = array(2,"item2");
$arr[] = array(1,"item3");
//$arr[] = ...
//doesn't work
function foo($x) {
global $arr; // some Array
foreach($arr as $value) {
if($value[0] == $x) {
echo $value[1]."\n";
foo($value[0]);
}
}
}
//just use this
function foo($x) {
global $arr; // some Array
for($i=0; $i < count($arr); $i++) {
if($arr[$i][0] == $x) {
echo $arr[$i][1]."\n";
foo($arr[$i][0]);
}
}
}
Paul
http://php.net/manual/en/control-structures.foreach.php