in_array() / array_search() / array_key_exists() Since: PHP 4(2000)
Functions for searching whether a specific value or key exists in an array. Commonly used in conditional branching and validation.
Syntax
// Checks whether a value exists in an array. in_array(value, array, strict); // Searches for a value in an array and returns the corresponding key. array_search(value, array, strict); // Checks whether a specified key exists in an array. array_key_exists(key, array);
Function List
| Function | Description |
|---|---|
| in_array($needle, $haystack, $strict) | Returns true if the specified value exists in the array. |
| array_search($needle, $haystack, $strict) | Searches for a value in the array and returns the corresponding key if found. Returns false if not found. |
| array_key_exists($key, $array) | Returns true if the specified key exists in the array. Returns true even if the value is null. |
Sample Code
<?php
$fruits = ['apple', 'orange', 'grape', 'peach'];
// Check whether a value exists in the array.
if (in_array('orange', $fruits)) {
echo 'Found'; // Outputs 'Found'.
}
// Search for a value and get its position.
$index = array_search('grape', $fruits);
echo $index; // Outputs '2'.
// Check for key existence in an associative array.
$user = ['name' => 'Taro', 'age' => 25, 'email' => null];
echo array_key_exists('name', $user); // Outputs '1'. true.
echo array_key_exists('phone', $user); // Outputs nothing. false.
// Compare array_key_exists and isset.
echo array_key_exists('email', $user); // Outputs '1'. Returns true even when the value is null.
echo isset($user['email']); // Outputs nothing. isset returns false when the value is null.
// Understanding the importance of strict comparison.
$values = [0, false, null, '', '0'];
echo in_array(false, $values); // Outputs '1'.
echo in_array(false, $values, true); // Outputs '1'. Uses strict comparison.
echo in_array(0, $values, true); // Outputs '1'. A strictly matching type exists.
Notes
Both in_array() and array_search() search for a value in an array, but they differ in their return values: in_array() returns a boolean indicating whether the value exists, while array_search() returns the key of the matching element.
It is strongly recommended to pass true as the third argument to enable strict comparison. Due to PHP's type coercion, loose comparison can produce unexpected results — for example, 0 == "string" evaluates to true.
Both array_key_exists() and isset() can check for key existence, but they behave differently when the value is null. array_key_exists() returns true as long as the key exists, while isset() returns false if the value is null. Choose the one that fits your use case.
To find common elements or differences between arrays, see array_intersect() / array_diff().
If you find any errors or copyright issues, please contact us.