PHP: Get key from array? PHP: Get key from array? arrays arrays

PHP: Get key from array?


You can use key():

<?php$array = array(    "one" => 1,    "two" => 2,    "three" => 3,    "four" => 4);while($element = current($array)) {    echo key($array)."\n";    next($array);}?>


Use the array_search function.

Example from php.net

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');$key = array_search('green', $array); // $key = 2;$key = array_search('red', $array);   // $key = 1;


$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');foreach($foo as $key => $item) {  echo $item.' is begin with ('.$key.')';}