search and replace value in PHP array

前端 未结 9 1035
一生所求
一生所求 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: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];
        }
    }
    

提交回复
热议问题