0
0
PhpHow-ToBeginner · 3 min read

How to Use array_search in PHP: Syntax and Examples

In PHP, array_search finds the key of a given value in an array. It returns the key if found, or false if the value is not present. Use it by passing the value to search and the array as arguments.
📐

Syntax

The array_search function has this syntax:

  • array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

$needle is the value you want to find.

$haystack is the array to search in.

$strict (optional) checks type too if set to true.

php
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false
💻

Example

This example shows how to find the key of a value in an array using array_search. It prints the key if found or a message if not.

php
<?php
$fruits = ['apple', 'banana', 'cherry'];
$key = array_search('banana', $fruits);

if ($key !== false) {
    echo "Found 'banana' at key: $key";
} else {
    echo "'banana' not found in the array.";
}
?>
Output
Found 'banana' at key: 1
⚠️

Common Pitfalls

One common mistake is not using the strict parameter when types matter. For example, searching for the integer 0 might return unexpected results if the array contains strings like '0'.

Also, since array_search returns false if not found, always use !== false to check the result to avoid confusion with key 0.

php
<?php
// Wrong way: using == can cause errors
$numbers = [0 => 'zero', 1 => 'one'];
$result = array_search(0, $numbers);
if ($result == false) {
    echo "Not found"; // This runs incorrectly because key 0 == false
}

// Right way: use !== false
$result = array_search(0, $numbers);
if ($result !== false) {
    echo "Found at key: $result"; // Correctly prints key 0
}
?>
Output
Found at key: 0
📊

Quick Reference

ParameterDescription
$needleValue to search for in the array
$haystackArray to search in
$strictOptional boolean to check type strictly (default false)
ReturnKey of found value or false if not found

Key Takeaways

Use array_search to find the key of a value in an array.
Always check the result with !== false to handle key 0 correctly.
Set the strict parameter to true to compare types exactly.
If the value is not found, array_search returns false.
array_search works with both indexed and associative arrays.