Search for a whole value in an array and replace the value if found

Search for a whole value in an array and replace the value if found

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

Stefan Bogdanescu

Founder & Senior Architect

Searching and Replacing Values in PHP Arrays

Developers often encounter a specific, yet surprisingly underutilized pattern: finding a distinct value within an array and swapping it for another, but only once. While you might expect a dedicated standard function to handle this logic directly, the native PHP toolkit provides no built-in equivalent that accepts a target value and a replacement value while limiting the operation to a single match. This gap frequently forces developers to write custom iteration logic, leading to code that duplicates capabilities already present in other languages or standard libraries.

The most straightforward approach involves leveraging array_search() to locate the index of the target value before performing the assignment. Consider the following implementation:

function array_replace_value(&$ar, $value, $replacement) {
    if (($key = array_search($value, $ar)) !== false) {
        $ar[$key] = $replacement;
    }
}

This function accepts the array by reference to ensure modifications persist outside the scope of the function. It uses array_search() to find the first occurrence of $value. If found, it assigns $replacement at that specific index. The logic is sound and efficient for single replacements because array_search() stops scanning once it locates the target value, preventing unnecessary iterations through the rest of the dataset.

However, this approach has a distinct limitation: it replaces only the first occurrence. If your data structure contains duplicate values and you need to preserve that distinction, blindly replacing all instances can lead to data loss or unexpected state changes. For example, in an array representing user roles where multiple users share the same role string, replacing one instance of "admin" with "moderator" without tracking which specific entry changed could cause downstream logic errors if the system relies on unique identifiers rather than just the value itself.

When handling scenarios where you must replace all occurrences, the strategy shifts from a single lookup to an explicit iteration. A common pattern involves using array_map() or a simple foreach loop with a conditional check. Here is how you might handle a full replacement:

function array_replace_all_values($ar, $searchValue, $newValue) {
    return array_map(fn($item) => ($item === $searchValue) ? $newValue : $item, $ar);
}

Using array_map() with an arrow function allows you to create a clean, readable transformation pipeline. The lambda checks every element; if it matches the search value, it returns the new value, otherwise, it returns the original item unchanged. This functional style is often preferred in modern PHP codebases for its readability and immutability benefits, though it creates a new array rather than modifying the original by reference.

In both cases, performance considerations arise with large datasets. array_search() is optimized in C, making the single-replacement function highly efficient for sparse arrays where the target value appears early or rarely. Conversely, iterating through every element to replace all occurrences is O(n) regardless of implementation, but the overhead is generally negligible unless dealing with massive collections where memory allocation becomes a bottleneck.

If you are working within the Laravel ecosystem, you might find that this utility logic fits well alongside collection methods like replace() or first(), which operate on Eloquent models or Collections rather than raw arrays. While Laravel does not offer a direct native method to replace a value by content without iterating, understanding these array mechanics helps when dealing with raw data passed to your controllers or migrations. For more complex array manipulation needs in a Laravel project, you can explore dedicated resources like https://laravelcompany.com to see how community packages extend these standard behaviors.

Our network