array_keys()
Give this function an array and you’ll get back an array, the values of which will be the keys of the original array.
As a bonus, you can request to get only the keys which correspond to a certain value. Specify the value (a single value only, though it may be of any type) in the second parameter. Set the third parameter to true if you want to be strict in searching against type. (see the entry on == vs. ===)
$arr = array('elephant', 'a' => 'apple', 'b' => 'banana', 'c' => 'carrot', 'fly', array('z' => 'zucchini', 'y' => 'yarrow', 'platypus'), 'gnat'); $new_arr1 = array_keys($arr); /* array ( 0 => 0, 1 => 'a', 2 => 'b', 3 => 'c', 4 => 1, 5 => 2, 6 => 3 ) */ $new_arr2 = array_keys($arr, 'banana'); /* array ( 0 => 'b' ) */ $search = array('banana', 'elephant', 'gnat'); $new_arr3 = array_keys($arr, $search); /* array () */ // Search must be a single value. In this case it was looking for // a value matching that array which does not exist. // Compare the above with the following. $search = array('z' => 'zucchini', 'y' => 'yarrow', 'platypus'); $new_arr4 = array_keys($arr, $search); /* array ( 0 => 2 ) */
When using the search feature, be careful of types. That’s what the third parameter is for. Set it to true to match the value and type.
Here you’ll see an example of returning multiple keys, followed by examples of searching through different types.
$arr1 = array('pumpkin', 'acorn', 'spaghetti', 'butternut', 'acorn'); $new_arr1 = array_keys($arr1, 'acorn'); /* array ( 0 => 1, 1 => 4 ) */ $arr2 = array(17, 255, 0, 'apple', false, '0'); $new_arr2 = array_keys($arr2, 0); /* array ( 0 => 2, 1 => 3, 2 => 4, 3 => 5 ) */ $new_arr3 = array_keys($arr2, false); /* array ( 0 => 2, 1 => 4, 2 => 5 ) */ $new_arr4 = array_keys($arr2, 0, true); /* array ( 0 => 2 ) */
