How to get numeric key of new pushed item in PHP?
$arr[] = $new_item;
Is it possible to get the newly pushed item programmatically?
Note that it's not necessary count($arr)-1
:
$arr[1]=2;
$arr[]开发者_如何学运维 = $new_item;
In the above case,it's 2
end()
do the job , to return the value ,
if its help to you ,
you can use key()
after to petch the key.
after i wrote the answer , i see function in this link :
http://www.php.net/manual/en/function.end.php
function endKey($array){
end($array);
return key($array);
}
max(array_keys($array))
should do the trick
The safest way of doing it is:
$newKey = array_push($array, $newItem) - 1;
You can try:
max(array_keys($array,$new_item))
array_keys($array,$new_item)
will return all the keys associated with value $new_item
, as an array.
Of all these keys we are interested in the one that got added last and will have the max
value.
You could use a variable to keep track of the number of items in an array:
$i = 0;
$foo = array();
$foo[++$i] = "hello";
$foo[++$i] = "world";
echo "Elements in array: $i" . PHP_EOL;
echo var_dump($foo);
if it's newly created, you should probably keep a reference to the element. :)
You could use array_reverse
, like this:
$arr[] = $new_item;
...
$temp = array_reverse($arr);
$new_item = $temp[0];
Or you could do this:
$arr[] = $new_item;
...
$new_item = array_pop($arr);
$arr[] = $new_item;
If you are using the array as a stack, which it seems like you are, you should avoid mixing in associative keys. This includes setting $arr[$n]
where $n > count($arr)
. Stick to using array_*
functions for manipulation, and if you must use indexes only do so if 0 < $n < count($arr)
. That way, indexes should stay ordered and sequential, and then you can rely on $arr[count($arr)-1]
to be correct (if it's not, you have a logic error).
精彩评论