3

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.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268

10 Answers10

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

foreach($myarray as $key => $val)
{
    if ($val == 'search1') $myarray[$key] = 'search4';
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • A pretty straight forward and simple solution – brenjt Aug 22 '11 at 02:37
  • 2
    @Alfacinha: If an answer has solved your problem, you should accept it by clicking the check-mark to it's left, so that other's coming to this post will know that it's the right solution. – Joseph Silber Aug 22 '11 at 02:46
  • 1
    Pro: it's basic code every PHP developer is familiar with. Con: it's slower than the function meant for this operation, `array_map()`. Con: the initial array is edited in-place, which can be sometimes handy but is usually a bad practice, especially since it makes it hard to define unit test on this code. –  Aug 22 '11 at 02:51
2

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.

2
$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" );
foreach($myarray as $key => $val)
{
    if ($val == 'search1' and $key == $user )
    {
       $myarray[$key] = 'search4';
       break;
    }
}
print_r($myarray);

Prints:

Array
(
    [user1] => search4
    [user2] => search2
    [user3] => search1
)
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • 1
    Make sure you add `break;` inside the `if` to stop iterating after the key has been found. No point iterating over the entire array if the value has already been set. – adlawson Aug 22 '11 at 03:00
2

Why not just do

if (isset($myarray[$user])) $myarray[$user] = 'search4';
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Search and replace inside an associative array or numeric Replace value in any associative array and array can be any deep

function array_value_replace($maybe_array, $replace_from, $replace_to) {

    if (!empty($maybe_array)) {
        if (is_array($maybe_array)) {
            foreach ($maybe_array as $key => $value) {
                $maybe_array[$key] = array_value_replace($value, $replace_from, $replace_to);
            }
        } else {
            if(is_string($maybe_array)){
                $maybe_array = str_replace($replace_from, $replace_to, $maybe_array);
            }               
        }
    }

    return $maybe_array;
}
realmag777
  • 2,050
  • 1
  • 24
  • 22
0

if you want for particular key then you just add condition for key in previous ans like.

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

foreach($myarray as $key => $val)
{
    if ($val == 'search1' && $key == $user) $myarray[$key] = 'search4';
}
Divyesh Jesadiya
  • 1,105
  • 4
  • 30
  • 68
  • Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its educational value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Jun 28 '17 at 15:55
0
$originalArray = array( "user1" => "search1" , "user2" => "search2" );
$pattern = 'search1';
$replace = 'search4';

$replacedArray = preg_replace( '/'.$pattern.'/' , $replace , $originalArray );

Fixes the risk mentioned in comment in response to this solution

Community
  • 1
  • 1
Luke Stevenson
  • 10,357
  • 2
  • 26
  • 41
0

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.

Community
  • 1
  • 1
adlawson
  • 6,303
  • 1
  • 35
  • 46
-1

Using str_replace should work:

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

$newArray = str_replace('search1', 'search4', $myarray);
Doug Kress
  • 3,537
  • 1
  • 13
  • 19
  • This is dangerous code. If the array contained the value "search12", it would be changed to "search42". –  Aug 22 '11 at 02:42
  • I actually thought that was the desired outcome - search and replace vs. value replacement. Perhaps I misunderstood the question. – Doug Kress Aug 22 '11 at 02:45
-1

Following on from Joseph's answer, using preg_replace may enable you to use the code in other situations:

function pregReplaceInArray($pattern,$replacement,$array) {
    foreach ($array as $key => $value) {
        $array[$key] = preg_replace($pattern,$replacement,$value);
    }   
    return $array;
}
Pete
  • 2,196
  • 1
  • 17
  • 25