在 php 开发中,我们常常需要判断一个值是否在数组中。如果某个值在数组中,我们可以直接使用 in_array() 函数来判断,但是如果某个值不在数组中,该如何判断呢?本文将介绍多种方法判断某个值在不在数组中。
方法一:使用 in_array() 函数取反
in_array() 函数可以判断一个值是否在数组中,如果不在,返回 false。
我们可以利用此特性来判断某个值不在数组中。
代码示例:
立即学习“PHP免费学习笔记(深入)”;
$needle = 'apple';
$fruits = ['banana', 'orange', 'grape'];
if (!in_array($needle, $fruits)) {
echo $needle . ' is not in the fruits array.';
}输出结果:
apple is not in the fruits array.
方法二:使用 array_search() 函数
array_search() 函数可以在数组中搜索一个值,并返回该值的键名。如果值不在数组中,返回 false。
我们可以利用此特性来判断某个值不在数组中。
代码示例:
立即学习“PHP免费学习笔记(深入)”;
$needle = 'apple';
$fruits = ['banana', 'orange', 'grape'];
if (array_search($needle, $fruits) === false) {
echo $needle . ' is not in the fruits array.';
}输出结果:
apple is not in the fruits array.
方法三:使用 array_diff() 函数
array_diff() 函数可以计算出两个或多个数组的差集,也就是说,它可以找出不在数组中的值。
我们可以将要判断的值作为一个只有一个元素的数组与原数组进行差集计算,如果差集的结果为空数组,则说明要判断的值不在原数组中。
代码示例:
立即学习“PHP免费学习笔记(深入)”;
$needle = 'apple';
$fruits = ['banana', 'orange', 'grape'];
if (empty(array_diff([$needle], $fruits))) {
echo $needle . ' is not in the fruits array.';
}输出结果:
apple is not in the fruits array.
方法四:使用 count() 函数
我们可以使用 count() 函数获取数组中元素的个数,判断要查找的值在原数组中出现的次数,如果次数为 0,则说明该值不在原数组中。
代码示例:
立即学习“PHP免费学习笔记(深入)”;
$needle = 'apple';
$fruits = ['banana', 'orange', 'grape'];
if (count(array_keys($fruits, $needle)) === 0) {
echo $needle . ' is not in the fruits array.';
}输出结果:
apple is not in the fruits array.
方法五:使用 foreach 循环
我们可以使用 foreach 循环遍历数组,查找要判断的值是否在数组中。如果遍历完数组仍然没有找到要判断的值,则说明该值不在数组中。
代码示例:
立即学习“PHP免费学习笔记(深入)”;
$needle = 'apple';
$fruits = ['banana', 'orange', 'grape'];
$found = false;
foreach ($fruits as $fruit) {
if ($fruit === $needle) {
$found = true;
break;
}
}
if (!$found) {
echo $needle . ' is not in the fruits array.';
}输出结果:
apple is not in the fruits array.
方法六:使用 array_key_exists() 函数
如果数组的键名是字符串,我们可以使用 array_key_exists() 函数判断某个键名是否在数组中存在。
代码示例:
立即学习“PHP免费学习笔记(深入)”;
$needle = 'apple';
$fruits = ['banana' => 1, 'orange' => 1, 'grape' => 1];
if (!array_key_exists($needle, $fruits)) {
echo $needle . ' is not in the fruits array.';
}输出结果:
apple is not in the fruits array.
结束语
本文介绍了多种方法判断某个值不在数组中。每种方法都有其优缺点,我们可以根据具体情况选择最适合的方法。在实际开发中,我们也可以结合具体场景,灵活运用这些技巧,提高开发效率和代码质量。
以上就是php怎么判断某个值在不在数组中的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号