In PHP, there are many ways to determine whether an array contains a certain value. This article will introduce several of them.
Method 1: Use the in_array() function
The in_array() function is a function in PHP used to check whether a certain value exists in an array. Its syntax is as follows:
in_array($value, $array);
Among them, $value is the value to be found, and $array is the array to be found. Returns true if the value is found in the array, false otherwise.
Sample code:
<?php $fruits = array("apple", "banana", "orange", "pear"); if (in_array("banana", $fruits)) { echo "找到了!"; } else { echo "没有找到!"; } ?>
Output result:
找到了!
Method 2: Use array_search() function
array_search() function is also used in arrays Find a specific value. Its syntax is as follows:
array_search($value, $array);
Among them, $value is the value to be found, and $array is the array to be found. If the value is found, its key name is returned, otherwise false is returned.
Sample code:
<?php $fruits = array("apple", "banana", "orange", "pear"); $key = array_search("banana", $fruits); if ($key !== false) { echo "找到了,键名为:" . $key; } else { echo "没有找到!"; } ?>
Output result:
找到了,键名为:1
Method 3: Use isset() function and key name
If you don’t care about the specific value, If you just want to determine whether a certain key exists in the array, you can also use the isset() function. If the key exists, returns true, otherwise returns false.
Sample code:
<?php $fruits = array("apple" => 1, "banana" => 2, "orange" => 3, "pear" => 4); if (isset($fruits["banana"])) { echo "找到了!"; } else { echo "没有找到!"; } ?>
Output result:
找到了!
Method 4: Use the array_key_exists() function
Similar to the isset() function, array_key_exists() Functions can also be used to check whether a key exists in an array. If the key exists, returns true, otherwise returns false.
Sample code:
<?php $fruits = array("apple" => 1, "banana" => 2, "orange" => 3, "pear" => 4); if (array_key_exists("banana", $fruits)) { echo "找到了!"; } else { echo "没有找到!"; } ?>
Output result:
找到了!
To sum up, there are many ways to determine whether an array contains a certain value in PHP. When using it, you can choose the appropriate method according to actual needs.
The above is the detailed content of How to determine whether an array contains a certain value in php. For more information, please follow other related articles on the PHP Chinese website!