search and replace value in PHP array

前端 未结 9 1052
一生所求
一生所求 2020-12-08 19:43

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:

         


        
9条回答
  •  悲&欢浪女
    2020-12-08 20:20

    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.

提交回复
热议问题