note 94943 added to function.end

From: Date: Thu, 03 Dec 2009 18:07:15 +0000
Subject: note 94943 added to function.end
Groups: php.notes 
Request: Send a blank email to php-notes+get-163548@lists.php.net to get a copy of this message
To comment on y dot vecchi at gmail dot com 's post To see if foreach is in last element of array in PHP5 you can use the end() function... This will not work correctly if the value of the last element is the same as another value in the array <?php $test = array( 5, 4, 3, 2, 1 ); foreach($test as $value) { if (end($test) == $value) { echo "I'm the last"; } } ?> You must compare the current key to the last key, because the keys in an array will be unique... A solution is to use array_pop(array_keys($list)), which returns the last key in the array (I found this in another post somewhere)... The following determines if the key IS NOT the last, which is what I need more often than IS the last <?php $list = array('1','9','3','7','9'); foreach($list as $key => $value) { echo $value; if(!(array_pop(array_keys($list)) == $key)) { echo '<br />'; } } echo " IS THE LAST"; ?> Will output: 1 9 3 7 9 IS THE LAST ---- Server IP: 69.147.83.197 Probable Submitter: 69.128.124.66 ---- Manual Page -- http://www.php.net/manual/en/function.end.php Edit -- https://master.php.net/note/edit/94943 Del: integrated -- https://master.php.net/note/delete/94943/integrated Del: useless -- https://master.php.net/note/delete/94943/useless Del: bad code -- https://master.php.net/note/delete/94943/bad+code Del: spam -- https://master.php.net/note/delete/94943/spam Del: non-english -- https://master.php.net/note/delete/94943/non-english Del: in docs -- https://master.php.net/note/delete/94943/in+docs Del: other reasons-- https://master.php.net/note/delete/94943 Reject -- https://master.php.net/note/reject/94943 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#163548) next »