search and replace value in PHP array search and replace value in PHP array arrays arrays

search and replace value in PHP array


Instead of a function that only replaces occurrences of one value in an array, there's the more general array_map:

array_map(function ($v) use ($value, $replacement) {    return $v == $value ? $replacement : $v;}, $arr);

To replace multiple occurrences of multiple values using array of value => replacement:

array_map(function ($v) use ($replacement) {    return isset($replacement[$v]) ? $replacement[$v] : $v;}, $arr);

To replace a single occurrence of one value, you'd use array_search as you do. Because the implementation is so short, there isn't much reason for the PHP developers to create a standard function to perform the task. Not to say that it doesn't make sense for you to create such a function, if you find yourself needing it often.


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    ));


If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.

$replacements = array(    'search1' => 'replace1',    'search2' => 'replace2',    'search3' => 'replace3');foreach ($a as $key => $value) {    if (isset($replacements[$value])) {        $a[$key] = $replacements[$value];    }}