php array get key name based on value

php array get key name based on value

 
 

The php array obtains the key name function according to the value. There are mainly two built-in functions that can be used. array_search and array_keys are used to handle returning a single key name and multiple key names.
Specific examples are as follows:

 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
/**
  * php array get key by value
  * php数组根据值获取键名
  * @author http://www.phpff.com
  */
$items = array (
     "banana" => "fruit" ,
     "tomato" => "vegetable" ,
     "lentil" => "bean" ,
     "apple"  => "vegetable"
);
 
//1.返回一个键名,如果值有重复返回第一个键名
$key = array_search ( 'vegetable' , $items );
 
echo $key ; //tomato
 
//2.返回多个键名
$keys = array_keys ( $items , 'vegetable' );
 
print_r( $keys );
/*
Array
(
     [0] => tomato
     [1] => apple
)
*/
?>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325035441&siteId=291194637