0
0
PhpHow-ToBeginner · 3 min read

How to Search in Array PHP: Simple Methods Explained

In PHP, you can search in an array using in_array() to check if a value exists, or array_search() to find the key of a value. These functions help you quickly find if an item is present and where it is located in the array.
📐

Syntax

in_array() checks if a value exists in an array and returns true or false.

array_search() returns the key of the found value or false if not found.

php
$exists = in_array($needle, $haystack, $strict = false);
$key = array_search($needle, $haystack, $strict = false);
💻

Example

This example shows how to check if a value exists and how to find its key in an array.

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

// Check if 'banana' is in the array
if (in_array('banana', $fruits)) {
    echo "Banana is in the list.\n";
} else {
    echo "Banana is not in the list.\n";
}

// Find the key of 'cherry'
$key = array_search('cherry', $fruits);
if ($key !== false) {
    echo "Cherry found at index: $key\n";
} else {
    echo "Cherry not found.\n";
}
?>
Output
Banana is in the list. Cherry found at index: 2
⚠️

Common Pitfalls

One common mistake is not using the strict parameter when searching, which can cause unexpected matches due to type juggling.

Also, array_search() returns false if not found, but the key 0 is also considered false in PHP, so always use !== false to check the result.

php
<?php
$numbers = [0, 1, 2];

// Wrong check - might fail if key is 0
$key = array_search(0, $numbers);
if ($key) {
    echo "Found at index $key\n";
} else {
    echo "Not found\n";
}

// Correct check
if ($key !== false) {
    echo "Found at index $key\n";
} else {
    echo "Not found\n";
}
?>
Output
Not found Found at index 0
📊

Quick Reference

FunctionPurposeReturn Value
in_array(needle, haystack, strict)Check if value existstrue or false
array_search(needle, haystack, strict)Find key of valuekey or false
strpos(haystack, needle)Find substring position in stringposition or false

Key Takeaways

Use in_array() to check if a value exists in an array.
Use array_search() to find the key of a value and always check with !== false.
Set the strict parameter to true to avoid type-related mismatches.
Remember that array_search() can return 0, which is a valid key, so avoid loose checks.
For searching inside strings, use strpos() instead of array functions.