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)
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)
<?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;
?>
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]; ... }
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
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'];