Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array key from corresponding array value?

Tags:

arrays

php

You can easily get an array value by its key like so: $value = array[$key] but what if I have the value and I want its key. What's the best way to get it?

like image 781
JD Isaacks Avatar asked Jun 02 '10 17:06

JD Isaacks


People also ask

How do you find the key of an array?

You can use array_keys() to get ALL the keys of an array, e.g.

How do you find the key and value of an array?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.

Can array key be an array?

As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string.


2 Answers

You could use array_search() to find the first matching key.

From the manual:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');  $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array);   // $key = 1; 
like image 196
Pekka Avatar answered Sep 19 '22 20:09

Pekka


You can use the array_keys function for that.

Example:

$array = array("blue", "red", "green", "blue", "blue"); print_r(array_keys($array, "blue")); 

This will get the key from the array for value blue

like image 45
Sarfraz Avatar answered Sep 18 '22 20:09

Sarfraz