search and replace value in PHP array

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

    Based on Deept Raghav's answer, I created the follow solution that does regular expression search.

    $arr = [
        'Array Element 1',
        'Array Element 2',
        'Replace Me',
        'Array Element 4',
    ];
    
    $arr = array_replace(
        $arr,
        array_fill_keys(
            array_keys(
                preg_grep('/^Replace/', $arr)
            ),
            'Array Element 3'
        )
    );
    
    echo '
    ', var_export($arr), '
    ';

    PhpFiddle: http://phpfiddle.org/lite/code/un7u-j1pt

提交回复
热议问题