tags:

views:

68

answers:

5
$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

A: 

max(array_keys($array)) ?

Bryan Ross
+1  A: 

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);
}
Haim Evgi
I don't think that will work. From the PHP Docs:"Every array has an internal pointer to its 'current' element, which is initialized to the first element inserted into the array." It's possible `end()` might do the job
Bryan Ross
i fix it , you right , its end()
Haim Evgi
A: 

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);
TheMagician
This will overwrite existing keys, and if there are none offers no benefit over just using `$foo[]`, apart from making a one-based array (which may or may not be a benefit).
Duncan
A: 

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.

codaddict
A: 

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).

Duncan