note 95316 deleted from function.end by danbrown
| From: | danbrown@php.net | Date: | Sun, 27 Dec 2009 20:10:51 +0000 |
| Subject: | note 95316 deleted from function.end by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-164365@lists.php.net to get a copy of this message | ||
Note Submitter: alexander at example dot com
----
I want to unite some previous notes. I needed to see if it was the last element of array in foreach
and there is no in-built function for it.
To y dot vecchi at gmail dot com:
Your code will not work properly if a few elements of array have the same value with the last one.
All these will be counted as last elements. Here goes my code:
<?php
//Warning: we do NOT get the reference to actual key this way
function lastkey($myarray = 1) {
//if we did not send argument, it goes as not array argument (integer here)
//checking
if (!is_array($myarray)) return null;
//no need to check if the array is empty - we shall get false in this case
//so we can know if it was empty array (result is false) or not array (result is null)
$allmykeys = array_keys($myarray);
return end($allmykeys);
//note: or use code mentioned by jasper at jtey dot com
//it seems alright except it does not check array
//so just add checking at the beginning of his function if you like it
}
$somearray = array(1 => 'one', 'two', 'three' =>
'three', '3' => 'three');
foreach ($somearray as $key => $value) {
if($key == lastkey($somearray)) echo "Last key is ".$key." and last value is
".$value;//it shows key 3, not 'three'
}
//no errors here
echo lastkey()===null;//1
echo lastkey(null)===null;//1
echo lastkey(12)===null;//1
echo lastkey(array())===false;//1
?>