array - find last inserted key

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
asgerhallas
Forum Commoner
Posts: 80
Joined: Tue Mar 14, 2006 11:11 am
Location: Århus, Denmark

array - find last inserted key

Post by asgerhallas »

I have this short script:

Code: Select all

$a[]="one";
$a[]="two";
$a[]="three";
What's the best way to find key of the last inserted item?

/Asger
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

array_keys()

usage:

Code: Select all

$key = array_keys($array,"value_to_find_keys_for");
print_r($key);
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
asgerhallas
Forum Commoner
Posts: 80
Joined: Tue Mar 14, 2006 11:11 am
Location: Århus, Denmark

Post by asgerhallas »

Ok, thanks!

But then sometimes it can be something like this:

Code: Select all

$a[]="";
$a[]="";
$a[]="";
Where all the values are the same, so I can't use the search_value. What do I do then?

I've tried this:

Code: Select all

end($a);
echo key($a);
But I can't figure if it will always give me the latest inserted key? What if I sort it for example?
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

hmm

im sure there's a better way than this
but this will work

Code: Select all

foreach($array AS $k=>$v){
   if(!empty($v)){
      $lastKey = $k;
   }
}

echo $lastKey;
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

This will work

Code: Select all

echo end(array_keys($a));
asgerhallas
Forum Commoner
Posts: 80
Joined: Tue Mar 14, 2006 11:11 am
Location: Århus, Denmark

Post by asgerhallas »

That works. Thanks a lot!
Post Reply