PHP: Check if Value in Array

You can use the in_array() function to check if a value exists in an array.

The sample code is as follows:

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

if (in_array("banana", $fruits)) {
    echo "数组中存在banana";
} else {
    echo "数组中不存在banana";
}

The output shows that “banana” is present in the array.

Additionally, you can use the array_search() function to get the key of a particular value in an array, and it will return false if the value does not exist. Here is an example code:

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

$key = array_search("banana", $fruits);

if ($key !== false) {
    echo "数组中存在banana,键值为:" . $key;
} else {
    echo "数组中不存在banana";
}

The output is: “banana” exists in the array with a key value of 1.

bannerAds