search and replace value in PHP array

前端 未结 9 1004
一生所求
一生所求 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:09
     <b>$green_key = array_search('green', $input); // returns the first key whose value is 'green'
    

    $input[$green_key] = 'apple'; // replace 'green' with 'apple'

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

    What about array_walk() with callback?

    $array = ['*pasta', 'cola', 'pizza'];
    $search = '*';
    $replace = '\*';
    array_walk($array,
        function (&$v) use ($search, $replace){
            $v = str_replace($search, $replace, $v);    
        }                                                                     
    );  
    print_r($array);
    
    0 讨论(0)
  • 2020-12-08 20:12

    Try this function.

    public function recursive_array_replace ($find, $replace, $array) {
        if (!is_array($array)) {
            return str_replace($find, $replace, $array);
        }
    
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key] = recursive_array_replace($find, $replace, $value);
        }
        return $newArray;
    }
    

    Cheers!

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

    Depending whether it's the value, the key or both you want to find and replace on you could do something like this:

    $array = json_decode( str_replace( $replace, $with, json_encode( $array ) ), true );
    

    I'm not saying this is the most efficient or elegant, but nice and simple.

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

    $ar[array_search('green', $ar)] = 'value';

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题