tags:

views:

225

answers:

4

Is there a better way to do the following:

$array = array('test1', 'test2', 'test3', 'test4', 'test5');
// do a bunch of other stuff, probably a loop
$array[] = 'test6';
end($array);
echo key($array); // gives me 6

This will give the key of the most recently add array element.

Is there a better way to do this?

+6  A: 

You could also do:

$end = end(array_keys($array));

But I think your way makes it clear what you want to do, so you could whip something up like:

function array_last_key($array) {
    end($array);
    return key($array);
}

That's about it.

Paolo Bergantino
I'd just like to throw out there that this is my biggest complaint with PHP. Negative array indices are definitely a good thing.
Robert Elwell
A: 

There is no special function for this in PHP, so I think your way is the most efficent way of doing this. For readability you might want to put it in a function called something like array_last_key().

yjerem
A: 

If you can guarantee that your array won't have any non-numerical keys and that you aren't going to be deleting any keys, then the last element added to your array's key will be

$last_added = count($array)-1;

If you really need to keep track of the latest added key, you may want to come up with a scheme to come up with your own keys that are guaranteed to be unique. this way you'll always have the latest added key since you generated it.

$array = array('test1', 'test2', 'test3', 'test4', 'test5');
// do a bunch of other stuff, probably a loop
$new_key = generate_key();
$array[$new_key] = 'test6';
echo $new_key; // gives me blahblahfoobar123
Keith Twombley
A: 

Simply put no. Both end and key are Big O(1) time. Any other way slows your code down and adds complexity.

gradbot
What do you mean by "Big O(1) time"?
Darryl Hein
The time stays the same, no matter how big your array gets
Greg