当我们在 PHP 中需要查找某个元素是否在一个数组中存在时,可以使用 in_array() 函数。in_array() 函数返回一个布尔值,表示要查找的元素在数组中是否存在。
当我们在 PHP 中需要查找某个元素是否在一个数组中存在时,可以使用 in_array() 函数。in_array() 函数返回一个布尔值,表示要查找的元素在数组中是否存在。
语法
该函数的语法如下:
in_array($needle, $haystack, $strict)
参数说明:
$needle:需要查找的元素。$haystack:被查找的数组,可以是关联数组或索引数组。$strict(可选):一个布尔值,表示是否进行类型匹配。默认为FALSE,即不进行类型匹配。
示例演示1
$fruits = array('apple', 'banana', 'orange');
if (in_array('banana', $fruits)) {
echo 'banana is found in the array';
} else {
echo 'banana is not found in the array';
}
输出结果:
banana is found in the array
示例演示2
$numbers = array(1, 2, '3', 4, '5');
if (in_array(3, $numbers)) {
echo '3 is found in the array';
} else {
echo '3 is not found in the array';
}
echo '<br>';
if (in_array(3, $numbers, true)) {
echo '3 is found in the array and has the same type';
} else {
echo '3 is not found in the array or has a different type';
}
输出结果:
3 is not found in the array
3 is not found in the array or has a different type
在第一个判断中,3 并未被找到,因为它是一个字符串类型,而数组中只有一个 '3' 字符串元素。
第二个判断中,我们在第三个参数中将 strict 设为了 true,这样可以进行类型匹配,结果将 '3' 剔除,判断结果为找不到 3。
总的来说,使用 in_array() 函数可以简单、快速的判断一个元素是否在数组中存在,对于一个大型的数组它的效率也比较高,因此开发中也比较常用。
编程基础网
本文标题为:php数组函数序列之in_array() 查找数组值是否存在
基础教程推荐
猜你喜欢
- PHP桥接模式Bridge Pattern的优点与实现过程 2023-07-12
- tp5.1 框架数据库常见操作详解【添加、删除、更新、查询】 2023-04-19
- PHP GD库添加freetype拓展的方法 2022-10-11
- php实现图片压缩处理 2023-05-01
- php万字码出完美守护进程详解 2023-06-26
- PHP实现读取文件夹及批量重命名文件操作示例 2023-01-08
- 【CLI】利用Curl下载文件实时进度条显示的实现 2022-10-12
- 在laravel5.2中实现点击用户头像更改头像的方法 2023-03-01
- 详解php用static方法的原因 2022-11-20
- Laravel5.5 动态切换多语言的操作方式 2023-03-11
