PHP if in_array() how to get the key as well?

PHP if in_array() how to get the key as well?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Keys from PHP Arrays When Checking for Values

The standard in_array() function is a staple in PHP, but it operates on a specific constraint: it returns a boolean indicating only whether a value exists, not where that value resides. In the scenario you presented, you have an associative array with non-sequential keys like [6] => 6, [3] => 5, and [2] => 7. You need to verify if 5 is present and immediately capture its associated key, which happens to be 3.

Because in_array() discards the position of the match, you cannot rely on it alone to retrieve the key. The most straightforward solution involves a simple two-step process or utilizing an alternative built-in function that exposes both pieces of information simultaneously.

The Two-Step Lookup Pattern

The most explicit way to achieve this is to use in_array() for validation and then perform a direct lookup using isset() or direct array access to retrieve the key. This approach separates the logic of existence from the logic of retrieval, making the code's intent very clear.

if (in_array(5, $array)) {
    // Find the key associated with the value 5
    foreach ($array as $key => $value) {
        if ($value === 5) {
            $foundKey = $key;
            break; 
        }
    }

    // Now use $foundKey (which is 3)
    echo "Found key: {$foundKey}"; 
} else {
    echo "Value not found.";
}

While this works, iterating through the array with a foreach loop inside an if block defeats the purpose of checking existence first. It adds unnecessary overhead if you are simply trying to check for the key after confirming the value. A more efficient pattern is to skip the boolean check entirely and assume the value exists, or handle the "not found" case by checking the result of the direct lookup.

Using array_search()

The built-in function array_search() was designed specifically to solve this exact problem. Unlike in_array(), which returns a boolean, array_search() returns the key of the first element that contains the specified value. If the value is not found, it returns false.

$key = array_search(5, $array);

if ($key !== false) {
    // $key will be 3 in your specific example
    echo "Value 5 is at key: {$key}";
    
    // You can now use $key to access other data or perform logic
    // using the original array structure if needed.
} else {
    // Handle the case where the value doesn't exist
}

This method is generally preferred over manual iteration because it is concise and optimized by PHP's internal engine. It handles both numeric and string keys correctly. In your specific case, array_search(5, $array) will return the integer 3.

Handling Associative Arrays with Duplicate Values

A critical detail to consider when using these functions is how they handle associative arrays with duplicate values. Your example shows an array where keys are not contiguous (0, 6, 3, 2), but the logic remains consistent. However, if your array contained multiple instances of the value 5, both in_array() and array_search() only return the key of the first match encountered.

If order is irrelevant to you, this is usually fine. If you need the last occurrence or a specific instance based on original insertion order, you would need a different approach, such as using array_flip() or iterating with strict conditions. But for standard existence checks where the first match suffices, array_search() is the direct answer.

Why Not Use array_key_exists()?

It is important to distinguish between checking for a key and checking for a value. If you know the key is 3 beforehand, you might consider using array_key_exists(3, $array). However, that checks if the integer 3 exists as a key, regardless of what value sits there. To check if the value at key 3 equals 5, you must still inspect the value:

if (isset($array[3]) && $array[3] === 5) {
    // Logic here
}

This requires you to already know the key, which brings us back to needing a function that finds the key based on the value. array_search() remains the correct tool for "find me the key given this value."

Summary of Best Practices

When you need both existence confirmation and the corresponding index:

  1. Prefer array_search(): It returns the key directly or false, removing the need for a separate boolean check.
  2. Avoid manual loops for simple lookups: Iterating manually is slower and less readable than utilizing built-in functions designed for array traversal.
  3. Watch out for duplicates: Remember that these functions return the first match, not all matches.

For developers working in modern PHP environments or specifically within the Laravel ecosystem, there are often wrapper methods provided by collections that make this even more readable. If you are already using Laravel, the collect() helper allows you to chain methods like firstWhere() which returns the entire item, and you can extract the key from that context if needed:

if ($user = collect($array)->firstWhere('value', 5)) {
    // Note: firstWhere works on associative arrays by matching value or key depending on implementation details.
    // In raw PHP arrays, array_search is often more direct for integer keys unless using a named collection pattern.
}

However, sticking to native array_search() ensures your code remains compatible across all standard PHP versions without requiring external packages or framework-specific knowledge, unless you are specifically leveraging the LaravelCompany resource for advanced collection helpers.

Our network