php数组 匹配键值

1、array_search()

//判断键值是否在数组中,
//存在,返回值对应的键;
//不存在,返回false;
//例子:
$type = array(
"选考" => 'optional',
"必考" => 'necessary',
"其他" => 'other',
);
echo $subject_type = array_search('optional',$type);
//输出:选考

2、in_array()

//和第一个类似,但是返回值不一样。
//如果typetrue,则判断类型;type不写,则不判断类型;
//搜索存在,返回:true; 反之,返回:false
$type = array(
"选考" => 'optional',
"必考" => 'necessary',
"其他" => 'other',
);
$res = in_array('optional',$type);

var_dump($res);//true

3、array_key_exists()

//该函数检查某个数组中是否存在指定的键名,
//如果键名存在则返回 true,如果键名不存在则返回 false
$search = array(
'first' => 1,
'second' => 4
);
if (array_key_exists('first', $search)) {
echo "The 'first' element is in the array";
}else{
echo "The 'first' element is not in the array";
}
//The 'first' element is in the array

----------------------------------------------------------

------------------------------------------------------------ 

array_key_exists() 与 isset() 的对比

isset() 对于数组中为 NULL 的值不会返回 TRUE,而 array_key_exists() 会。

$search_array = array('first' => null, 'second' => 4);

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array); 


记录点滴,迭代精进,追求新生。Email: 942298768@qq.com
原文地址:https://www.cnblogs.com/chaoyong/p/8137185.html