Search and replace inside an associative array

后端 未结 10 1859
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 22:14

I need to search and replace inside an associative array.

ex:

$user = \"user1\"; // I\'ve updated this

$myarray = array(\"user1\" => \"search1\",         


        
10条回答
  •  不知归路
    2021-01-20 22:45

    Updated

    Since the post was updated, and I have had chance to get some sleep, I realized my answer was stupid. If you have a given key and you need to change it's value, why iterate over the whole array?

    $user    = 'user1';
    $search  = 'search1';
    $replace = 'search4';
    $array   = array('user1' => 'search1', 'user2' => 'search2');
    
    if (isset($array[$user]) && $search === $array[$user]) $array[$user] = $replace;
    

    Similar to @Joseph's method (pretty much the same), but with a few tweaks:

    $user = 'user1';
    $array = array("user1" => "search1", "user2" => "search2" );
    
    foreach($array as $key => &$value) {
        if ($key === $user) {
            $value = 'search4';
            break; // Stop iterating after key has been found
        }
    }
    

    Passing by reference is a nicer way to edit inside foreach, and is arguably quicker.

提交回复
热议问题