tags:

views:

135

answers:

6

i have this array

Array
(
  [0] => a
  [1] => b
  [2] => c
  [3] => d
)

how can i get an element's key?(for example a=0,c=2)

+3  A: 

array_search()

chaos
You should be nominated for the 'Quickest answer' in the world :)
Seb
+4  A: 
<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

http://www.php.net/manual/en/function.array-flip.php

Using array_search http://php.net/manual/en/function.array-search.php

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>
Wbdvlpr
A: 

If you want to search, see array_search (http://www.php.net/manual/en/function.array-search.php)

If you are iterating over it, you can use various syntax:

foreach ($a as $key => $value) { ... }
foreach (array_keys($a) as $key) { $value = $a[$key]; ... }
wojo
A: 

array_keys:

array_keys($arr, 'a');         # 0
array_keys($arr, 'c');         # 2
SilentGhost
A: 

If you just want the keys use array_keys.

If you want to flip the array like you show in your example, use array_flip

Dooltaz
A: 

I personally like @SilentGhost's solution but you would suffer a speed penalty if you are doing more than one search, at which point you would want the following:

// assume you know you want the value for key 'c'
$array = ('a','b','c','d');
$keys = array_flip($array);
return $keys['c'];
cballou