开发者

PHP find element key

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;
?>


Use array_search()

Searches the array for a given value and returns the corresponding key if successful.

Example #1 array_search() example

<?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


array_keys:

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


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'];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜