Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the key of the current item of an array?

Tags:

arrays

php

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

like image 389
ajsie Avatar asked Feb 27 '10 17:02

ajsie


3 Answers

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)
like image 53
Pascal MARTIN Avatar answered Oct 19 '22 00:10

Pascal MARTIN


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

like image 8
Gumbo Avatar answered Oct 18 '22 23:10

Gumbo


You probably want key().

like image 5
Billy ONeal Avatar answered Oct 19 '22 00:10

Billy ONeal