Recursive Array Value Replacement in PHP

This code block represents a function that recursively replaces key-value pairs in an array. It is designed to maintain the original array structure while updating the values based on a search string and a replace string.

The function takes three parameters:

  • $array: The array to replace the values in.
  • $search: The search string to match values for replacement.
  • $replace: The replace string to substitute the matched values.

/**
 * Recursively replace the key-value pairs in an array.
 *
 * This function takes an array and recursively iterates through its elements,
 * replacing values that match a given search string with a replace string.
 * It preserves the original array structure while updating the values.
 *
 * @param array  $array   The array to replace the values in.
 * @param string $search  The search string.
 * @param string $replace The replace string.
 * @return array The array with replaced values.
 */
function replace_recursively($array, $search, $replace) {
    $new_array = array();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = $this->replace_recursively($value, $search, $replace);
        }
        $new_key = str_replace($search, $replace, $key);
        $new_value = str_replace($search, $replace, $value);
        $new_array[$new_key] = $new_value;
    }

    return $new_array;
}

The function starts by initializing a new array to store the modified values. It then iterates through each element of the input array. If the current element is itself an array, the function calls itself recursively to replace values within that subarray.

For each key-value pair encountered, the function applies the search and replace operations using the str_replace function, creating new key-value pairs with the updated values and storing them in the new array.

Finally, the function returns the new array with the replaced values, while preserving the original array structure.

This code is particularly useful when you need to perform a recursive search and replace operation on nested arrays, such as when modifying configuration settings or processing hierarchical data structures.