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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)