phparraysfilterreplace

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


I was looking for some standard PHP function to replace some value of an array with other, but surprisingly I haven't found any, so I have to write my own:

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

But I still wonder - for such an easy thing there must already be some function for it! Or maybe much easier solution than this one invented by me?

Note that this function will only do one replacement. I'm looking for existing solutions that similarly replace a single occurrence, as well as those that replace all occurrences.


Solution

  • While there isn't one function equivalent to the sample code, you can use array_keys (with the optional search value parameter), array_fill and array_replace to achieve the same thing:

    EDIT by Tomas: the code was not working, corrected it:

    $ar = array_replace($ar,
        array_fill_keys(
            array_keys($ar, $value),
            $replacement
        )
    );