note 95316 added to function.end
| From: | alexander at example dot com | Date: | Sun, 27 Dec 2009 01:33:51 +0000 |
| Subject: | note 95316 added to function.end | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-164336@lists.php.net to get a copy of this message | ||
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
?>
----
Server IP: 195.54.192.44
Probable Submitter: 95.25.171.241
----
Manual Page -- http://www.php.net/manual/en/function.end.php
Edit -- https://master.php.net/note/edit/95316
Del: integrated -- https://master.php.net/note/delete/95316/integrated
Del: useless -- https://master.php.net/note/delete/95316/useless
Del: bad code -- https://master.php.net/note/delete/95316/bad+code
Del: spam -- https://master.php.net/note/delete/95316/spam
Del: non-english -- https://master.php.net/note/delete/95316/non-english
Del: in docs -- https://master.php.net/note/delete/95316/in+docs
Del: other reasons-- https://master.php.net/note/delete/95316
Reject -- https://master.php.net/note/reject/95316
Search -- https://master.php.net/manage/user-notes.php