note 84112 deleted from function.next by danbrown
| From: | danbrown@php.net | Date: | Mon, 20 Apr 2009 23:30:01 +0000 |
| Subject: | note 84112 deleted from function.next by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-153524@lists.php.net to get a copy of this message | ||
Note Submitter: rayro at gmx dot de
----
@GPatmore and @gigs at gigstaggart dot com:
foreach() does not use the real array you are give in...
If you want to delete something in the array, the array passed through foreach() has to be a
reference to your array...
<?php
$my_array = explode(',','a,b,c,d,e,f,g');
$ary =& $my_array;
// Note: foreach(&ary => $a) wont work! Thats a little bit pity... :(
foreach($ary as $a){
print 'letter ' . $a;
if(next($ary)){
unset($ary[count($ary) - 1]);
print '<br>';
}else{
print '<br>dun!';
}
}
?>
would finally print:
letter a
letter b
letter c
letter d
dun!
Ohterwise you are able to make a while() as followed:
<?php
$ary = explode(',','a,b,c,d,e,f,g');
while(list($k,$a) = each($ary)) {
print 'letter ' . $a;
if(next($ary)){
prev($ary);
unset($ary[count($ary) - 1]);
print '<br>';
}else{
print '<br>dun!';
}
}
?>
Consider the prev() after the next()... ;)
This is essential for the each(), which means that YOU decide the pointer, while foreach() uses own
pointers...