PHP find element key

2019-08-27 08:13发布

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 arrays key
6条回答
太酷不给撩
2楼-- · 2019-08-27 08:52
<?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;
?>
查看更多
Summer. ? 凉城
3楼-- · 2019-08-27 08:58

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

查看更多
一纸荒年 Trace。
4楼-- · 2019-08-27 09:01

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;
?>
查看更多
Deceive 欺骗
5楼-- · 2019-08-27 09:03

array_keys:

array_keys($arr, 'a');         # 0
array_keys($arr, 'c');         # 2
查看更多
放我归山
6楼-- · 2019-08-27 09:04

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]; ... }
查看更多
【Aperson】
7楼-- · 2019-08-27 09:12

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'];
查看更多
登录 后发表回答