php怎么判断某值在不在数组中?

18次阅读
没有评论

在PHP中,可以使用in_array()函数来判断某个值是否在数组中。

$fruits = array("apple", "banana", "orange", "grape");

if (in_array("banana", $fruits)) {
    echo "Found banana in the array";
} else {
    echo "Couldn't find banana in the array";
}

输出结果为:

Found banana in the array

在上面的代码中,我们创建了一个包含几个水果的数组$fruits,然后使用in_array()函数来判断”banana”是否在数组中。由于该值存在于数组中,因此输出结果为”Found banana in the array”。

如果要判断的值不在数组中,那么输出结果将为”Couldn’t find banana in the array”,例如:

if (in_array("watermelon", $fruits)) {
    echo "Found watermelon in the array";
} else {
    echo "Couldn't find watermelon in the array";
}

输出结果为:

Couldn't find watermelon in the array

需要注意的是,in_array()函数区分大小写。如果要忽略大小写,可以使用array_map()函数和strtolower()函数来实现,例如:

$fruits = array("apple", "banana", "orange", "grape");

if (in_array("Banana", array_map('strtolower', $fruits))) {
    echo "Found Banana in the array";
} else {
    echo "Couldn't find Banana in the array";
}

输出结果为:

Found Banana in the array

在上面的代码中,我们将$fruits数组中所有元素都转换为小写字母,然后再使用in_array()函数来判断”Banana”是否在数组中。此时输出结果为”Found Banana in the array”,即使原来的数组中只有”banana”并没有”Banana”。

正文完
 
评论(没有评论)