如何在PHP中为关联数组执行in_array
问题描述:
Is there any PHP function to perform in_array()
for associative array? I know how to do with a foreach
loop, but is there a PHP function or more elegant way to do this?
是否有任何PHP函数可以为关联数组执行 in_array() code>? 我知道如何处理
foreach code>循环,但有没有PHP函数或更优雅的方法来做到这一点? p>
div>
答
Both in_array()
and array_search()
work just fine for associative arrays.
See these examples:
php > $array = ['one' => 1, 'two' => 2, 'three' => 3];
php > var_dump(in_array(2, $array));
bool(true)
php > var_dump(in_array(5, $array));
bool(false)
php > var_dump(array_search(2, $array));
string(3) "two"
php > var_dump(array_search(5, $array));
bool(false)
答
in_array() function is utilized to determine if specific value exists in an array.
It works fine for one dimensional numeric and associative arrays.
Please refer the following example code snippet which depicts the use of in_array function to check existence of value in an associative array.
$a=array();
$a['id']=1;
$a['name']='James';
$result=in_array('James',$a);
var_dump($result);