Searching for data within an array is one of the most common tasks in PHP. Whether you need to check if a value exists or find the key associated with a value, PHP has powerful built-in functions to help.
in_array()The in_array() function checks if a value exists in an array. It returns TRUE if the value is found, and FALSE otherwise.
<?php
$users = ["Alice", "Bob", "Charlie"];
if (in_array("Bob", $users)) {
echo "Bob is in the list!";
}
?>
array_search()If you need to find the key/index of a value, use array_search(). It returns the key if found, or FALSE if not.
<?php
$colors = ["a" => "red", "b" => "green", "c" => "blue"];
$key = array_search("green", $colors);
echo $key; // Output: b
?>
array_key_exists()To verify if a specific key exists in an associative array, use array_key_exists().
<?php
$scores = ["Math" => 95, "Science" => 88];
if (array_key_exists("Math", $scores)) {
echo "Math score is recorded.";
}
?>
in_array() and array_search() allow a third parameter (set to true) to perform a strict search (comparing both value and type).
| Function | What it returns | Best for |
|---|---|---|
in_array() | Boolean (True/False) | Quick presence check. |
array_search() | Key or False | Finding where an item is located. |
array_key_exists() | Boolean (True/False) | Verifying if a label/ID exists. |
in_array() for a simple yes/no if a value exists.array_search() when you need the position or key of a value.array_key_exists() to look up a specific identifier.true as 3rd param) to avoid unexpected type-juggling results.