
php如何根据某一个value获取其key
2022-09-28 · 百度认证:北京惠企网络技术有限公司官方账号

在一些PHP的场景之中可能会遇到,在PHP的数组中需要根据其中某一个value值来获取得到其key的值。这个时候就需要使用到PHP数组函数中的array_search()这个方法。
$array = array('test0','test1','test2');
$array1 = array('test0','test1','test2','test1');
$key = array_search('test1',$array);
$key1 = array_search('test1',$array1);
echo $key;
echo $key1;
输出都是1
如果有重复的value输出第一个相匹配的key
扩展资料
使用方法:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
//array_key_exists()的使用方法
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
//相关函数有
array_keys() - Return all the keys or a subset of the keys of an array
array_values() - Return all the values of an array
array_key_exists() - Checks if the given key or index exists in the array