note 70355 added to function.next

From: Date: Thu, 12 Oct 2006 19:14:11 +0000
Subject: note 70355 added to function.next
Groups: php.notes 
Request: Send a blank email to php-notes+get-118470@lists.php.net to get a copy of this message
If your using a foreach loop, unless you for a reference, PHP will make a copy of the array to use it the loop. So, when I need to take a different action for the last element in the array I use the following: <?php $ary = explode(',','a,b,c,d,e,f,g'); foreach($ary as $a){ print 'letter ' . $a; if(next($ary)){ print '<br>'; }else{ print '<br>dun!'; } } ?> Output: letter a letter b letter c letter d letter e letter f letter g dun! NOTE:: PHP5 has added an ability to reference the variable in a foreach like: <?php foreach($ary as &$a){} ?> this will probably cause undesired results when using the method above. also if the array is changed in any way as to cause the length of the original array to become different then the copy, it will not work. Consider the following example: <?php $ary = explode(',','a,b,c,d,e,f,g'); foreach($ary as $a){ print 'letter ' . $a; if(next($ary)){ unset($ary[count($ary) - 1]); print '<br>'; }else{ print '<br>dun!'; } } ?> output: letter a letter b letter c letter d dun!letter e dun!letter f dun!letter g dun! ---- Server IP: 64.71.164.2 Probable Submitter: 69.115.227.109 ---- Manual Page -- http://www.php.net/manual/en/function.next.php Edit -- https://master.php.net/note/edit/70355 Del: integrated -- https://master.php.net/note/delete/70355/integrated Del: useless -- https://master.php.net/note/delete/70355/useless Del: bad code -- https://master.php.net/note/delete/70355/bad+code Del: spam -- https://master.php.net/note/delete/70355/spam Del: non-english -- https://master.php.net/note/delete/70355/non-english Del: in docs -- https://master.php.net/note/delete/70355/in+docs Del: other reasons-- https://master.php.net/note/delete/70355 Reject -- https://master.php.net/note/reject/70355 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#118470) next »