search and replace value in PHP array

前端 未结 9 1043
一生所求
一生所求 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:35

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

提交回复
热议问题