一、基本介绍
PHP的array_search()函数是用来在数组中搜索指定的值,并返回其键名的函数。如果找到指定的值,则返回该值对应的键名,如果没有找到,则返回false。
array_search()函数的语法为:
mixed array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
其中,$needle为要搜索的值,$haystack为要搜索的数组,$strict为可选参数。如果该参数的值为true,则搜索时区分大小写和数据类型。
二、返回值
如果搜索成功,则返回键值,如果搜索失败,则返回false。需要注意的是,返回的键值是该值第一次出现在数组中的键名,而不是最后一次出现的键名。
下面的代码演示了array_search()函数的基本使用方法:
$arr = array('1'=>'apple', '2'=>'banana', '3'=>'cherry'); $index = array_search('banana', $arr); echo 'the index of \'banana\' is: '.$index; // 输出 2
三、值类型的判断
如果在搜索的数组中,值的类型不同,则需要使用第三个参数$strict,来确定搜索时是否区分类型。
下面的代码中,$arr数组中包含一个整数2和一个字符串’2’,如果不使用$strict,则无法区分它们:
$arr = array(1, 2, '2', '3'); $index = array_search('2', $arr); echo 'the index of \'2\' is: '.$index; // 输出 1 $index = array_search(2, $arr); echo 'the index of 2 is: '.$index; // 输出 1 $index = array_search('2', $arr, true); echo 'the index of \'2\' is: '.$index; // 输出 false
四、默认键名数组的搜索
如果要搜索的数组没有指定键名,则默认的键名是从0开始的数字索引。因此,如果搜索的值为0,则需要特别注意:
$arr = array(0, '1', '2'); $index = array_search(0, $arr); echo 'the index of 0 is: '.$index; // 输出 0
由于0为数组的默认键名,因此上面的代码输出的是0。
五、值为null或空字符串的搜索
如果要搜索的值为null或空字符串,则需要使用全等号(===)进行严格比较。因为array_search()函数使用的是弱类型比较(==),所以在搜索这些值时可能会出现一些问题。
$arr = array(null, '', 'foo', 'bar'); $index = array_search('', $arr); echo 'the index of \'\' is: '.$index; // 输出 0 $index = array_search(null, $arr); echo 'the index of null is: '.$index; // 输出 false $index = array_search(null, $arr, true); echo 'the index of null is: '.$index; // 输出 0
在上面的代码中,由于null和空字符串是不同类型的值,因此在搜索时需要使用严格比较。
六、多个结果的搜索
如果要搜索多个具有相同值的元素,则只返回最先找到的那个元素的键名。
$arr = array('apple', 'banana', 'cherry', 'banana'); $index = array_search('banana', $arr); echo 'the index of \'banana\' is: '.$index; // 输出 1
七、搜索区间的限制
如果只需要在数组的一部分中搜索,可以使用array_slice()函数,将需要搜索的部分切割成一个新的数组,再对该数组进行搜索。
$arr = array('apple', 'banana', 'cherry', 'orange'); $index = array_search('banana', array_slice($arr, 1, 2)); echo 'the index of \'banana\' is: '.$index; // 输出 false
在上面的代码中,将$arr数组从第二个元素开始切割,取两个元素进行搜索。由于这个部分没有banana元素,因此搜索失败。
八、使用回调函数进行搜索
如果需要自定义搜索的规则,则可以通过在array_search()函数中使用回调函数来实现。
function my_search($n) { return $n > 2; } $arr = array(1, 2, 3, 4, 5); $index = array_search(true, array_map('my_search', $arr)); echo 'the index of first number greater than 2 is: '.$index; // 输出 2
在上面的代码中,使用array_map()函数对数组中的每个元素应用my_search()函数,将结果转换为一个新的数组。然后在该数组中搜索true值,找到第一个大于2的元素的键名。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/229137.html