note 114730 added to control-structures.for
| From: | VincenzoRaco | Date: | Sun, 30 Mar 2014 16:59:12 +0000 |
| Subject: | note 114730 added to control-structures.for | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199074@lists.php.net to get a copy of this message | ||
In this code:
<?php
$array = array(
'pop0',
'pop1',
'pop2',
'pop3',
'pop4',
'pop5',
'pop6',
'pop7',
'pop8'
);
echo "Tot Before: ".count($array)."<br><br>";
for ($i=0; $i<count($array); $i++) {
if ($i === 3) {
unset($array[$i]);
}
echo "Count: ".count($array). " - Position: ".$i."<br>";
}
echo "<br> Tot After: ".count($array)."<br>";
?>
The result is:
---
Tot Before: 9
Count: 9 - Position: 0
Count: 9 - Position: 1
Count: 9 - Position: 2
Count: 8 - Position: 3
Count: 8 - Position: 4
Count: 8 - Position: 5
Count: 8 - Position: 6
Count: 8 - Position: 7
Tot After: 8
---
The position 8 is skipped, because the "expr2" {{ $i<count($array) }} is evaluated
again, for each cycle.
The solution is:
<?php
$array = array(
'pop0',
'pop1',
'pop2',
'pop3',
'pop4',
'pop5',
'pop6',
'pop7',
'pop8'
);
echo "Tot Before: ".count($array)."<br><br>";
$count = count($array);
for ($i=0; $i<$count; $i++) {
if ($i === 3) {
unset($array[$i]);
}
echo "Count: ".count($array). " - Position: ".$i."<br>";
}
echo "<br> Tot After: ".count($array)."<br>";
?>
----
Server IP: 81.88.49.18
Probable Submitter: 79.46.209.248
----
Manual Page -- http://php.net/manual/en/control-structures.for.php
Edit -- https://master.php.net/note/edit/114730
Del: integrated -- https://master.php.net/note/delete/114730/integrated
Del: useless -- https://master.php.net/note/delete/114730/useless
Del: bad code -- https://master.php.net/note/delete/114730/bad+code
Del: spam -- https://master.php.net/note/delete/114730/spam
Del: non-english -- https://master.php.net/note/delete/114730/non-english
Del: in docs -- https://master.php.net/note/delete/114730/in+docs
Del: other reasons-- https://master.php.net/note/delete/114730
Reject -- https://master.php.net/note/reject/114730
Search -- https://master.php.net/manage/user-notes.php