tags:

views:

77

answers:

3

When navigating through array with next() and prev(), how could you get the current key the array is at?

+6  A: 

Use the key function to get the key of the item the internal pointer is currently pointing to.

Gumbo
How dare you beat me by 47 seconds? +1
Billy ONeal
@BillyONeal: Moderators can travel back in time. ;-)
Gumbo
Well whoever was first should get the best answer. You're all right, obviously.
Brian Lacy
Agreed Brian Lacy. Just was trying to make a joke... failed miserably at that apparently.
Billy ONeal
@BillONeal: Fear not, I caught the jest, really was just commenting on the fact that three people gave the same correct answer in a matter of like two minutes. Of course it helps that the question was a simple one!
Brian Lacy
+9  A: 

You can use the key function :

key() returns the index element of the current array position.

And, as a quick example, you can consider this portion of code :

$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789, 
);

reset($array);      // Place pointer on the first element
next($array);       // Advance to the second one
$key = key($array); // Get the key of the current (i.e. second) element

var_dump($key);

It'll output, as expected, the key of the second element :

string 'second' (length=6)
Pascal MARTIN
How dare you beat me by 3 seconds? +1
Billy ONeal
Well, I suppose I don't have the ability to travel back in time... But I suppose I pressed F5 a couple of seconds before you did ^^
Pascal MARTIN
+4  A: 

You probably want key().

Billy ONeal