Difference Between array_search and in_array in PHP

In PHP, searching through arrays is a common task, often achieved using either in_array() or array_search(). While both functions are used to find values within an array, they serve different purposes and return different data types. This article explains the key differences between these two functions, how they work, and when to use each one in your PHP projects.

What is in_array()?

The in_array() function checks if a specific value exists in an array. It only cares about the existence of the value and does not tell you where the value is located.

Example:

$fruits = ['apple', 'banana', 'orange'];

if (in_array('banana', $fruits)) {
    echo "Banana is in the list!";
}

The array_search() function searches an array for a specific value and returns the corresponding key (index) of that value if it is found.

Example:

$fruits = ['apple', 'banana', 'orange'];

$key = array_search('banana', $fruits); // Returns 1
echo "Banana is at index: " . $key;

Key Differences

  1. Return Type:
    • in_array() returns a boolean (true or false).
    • array_search() returns the key of the element (int or string) if found, or false if not found.
  2. Use Case:
    • Use in_array() when you only need to verify whether an item exists in an array.
    • Use array_search() when you need to know the location (key/index) of the item to modify it, delete it, or use it later in your code.

The Importance of Strict Comparison

Both functions accept an optional third parameter called $strict. By default, this is set to false, meaning PHP will use loose comparison (==). This can lead to unexpected results due to PHP’s type juggling (for example, treating 0 as false or "5" as 5).

Setting the $strict parameter to true forces PHP to check both the value and the data type (===).

Example without strict mode:

$numbers = [0, 1, 2];
$key = array_search('0', $numbers); // Returns 0 (loose comparison matches '0' with 0)

Example with strict mode:

$numbers = [0, 1, 2];
$key = array_search('0', $numbers, true); // Returns false (strict comparison fails because '0' is a string and 0 is an integer)

How to Safely Check array_search() Results

Because array_search() can return 0 (a valid array index) which PHP can evaluate as false in loose comparisons, you must always use strict comparison (=== or !==) when checking the result of array_search().

$fruits = ['apple', 'banana', 'orange'];
$key = array_search('apple', $fruits); // Returns 0

// WRONG: This will evaluate to false because 0 is treated as false
if ($key) {
    echo "Found apple!";
}

// CORRECT: Uses strict comparison
if ($key !== false) {
    echo "Found apple at index " . $key;
}