Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace inside an associative array

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.

like image 895
Pedro Lobito Avatar asked Mar 22 '26 08:03

Pedro Lobito


2 Answers

$myarray = array("user1" => "search1", "user2" => "search2" );

foreach($myarray as $key => $val)
{
    if ($val == 'search1') $myarray[$key] = 'search4';
}
like image 58
Joseph Silber Avatar answered Mar 24 '26 22:03

Joseph Silber


There's a function for this : array_map().

// Using a lamba function, PHP 5.3 required
$newarray = array_map(
    function($v) { if ($v == 'search1') $v = 'search4'; return $v; },
    $myarray
);

If you don't want to use a lambda function, define a normal function or method and callback to it.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!