How to check if a value exists in an array in PHP?
In PHP, we can check if a value exists in an array by using in_array()
function.
Syntax:
in_array(search, array, type)
- search: Required. Specifies the what to search for.
- array: Required. Specifies the array to search.
- type: Optional. If this parameter is set to TRUE, the in_array() function searches for the search-string and specific type in the array.
Example:
$users = ['Sandeep', 'Kohli', 'Messi'];
$name = trim(fgets(STDIN));
if (in_array($name, $users)) {
echo "$name is an user.";
} else {
echo "$name is not an user.";
}
Output:
