note 94943 deleted from function.end by danbrown

From: Date: Thu, 03 Dec 2009 18:13:33 +0000
Subject: note 94943 deleted from function.end by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-163549@lists.php.net to get a copy of this message
Note Submitter: andrew bessa at gmail dot com ---- 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

« previous php.notes (#163549) next »