I need to search and replace inside an associative array.
ex:
$user = "user1"; // I've updated this
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" ) ;
I want to replace search1
for search4
. How can I achieve this?
UPDATE: I forgot to mention that the array has several search1
values and I just want to change the value where the key is == $user
. Sorry for not mention this earlier.
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?
Similar to @Joseph's method (pretty much the same), but with a few tweaks:
Passing by reference is a nicer way to edit inside
foreach
, and is arguably quicker.Search and replace inside an associative array or numeric Replace value in any associative array and array can be any deep
Prints:
Why not just do
if you want for particular key then you just add condition for key in previous ans like.