search and replace value in PHP array

前端 未结 9 1005
一生所求
一生所求 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 '<pre>', var_export($arr), '</pre>';
    

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

    0 讨论(0)
  • 2020-12-08 20:25

    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];
        }
    }
    
    0 讨论(0)
  • 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
        )
    );
    
    0 讨论(0)
提交回复
热议问题