Replace one value in array php

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:

function array_replace_value(&$ar, $value, $replacement)
{
    if (($key = array_search($ar, $value)) !== FALSE) {
        $ar[$key] = $replacement;
    }
}

But I still wonder - for such an easy thing there must already be some function for it! Or maybe much easier solution than this one invented by me?

Note that this function will only do one replacement. I'm looking for existing solutions that similarly replace a single occurrence, as well as those that replace all occurrences.

outis

73.2k19 gold badges146 silver badges216 bronze badges

asked Dec 29, 2011 at 14:05

Replace one value in array php

12

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.

answered Dec 29, 2011 at 14:19

outisoutis

73.2k19 gold badges146 silver badges216 bronze badges

5

While there isn't one function equivalent to the sample code, you can use array_keys (with the optional search value parameter), array_fill and array_replace to achieve the same thing:

EDIT by Tomas: the code was not working, corrected it:

$ar = array_replace($ar,
    array_fill_keys(
        array_keys($ar, $value),
        $replacement
    )
);

Replace one value in array php

Tomas

55.6k48 gold badges230 silver badges364 bronze badges

answered Dec 29, 2011 at 14:09

Deept RaghavDeept Raghav

1,41913 silver badges14 bronze badges

5

If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.

$replacements = array(
    'search2' => 'replace1',
    'search2' => 'replace2',
    'search3' => 'replace3'
);
foreach ($a as $key => $value) {
    if (isset($replacements[$value])) {
        $a[$key] = $replacements[$value];
    }
}

rmorse

7166 silver badges17 bronze badges

answered Sep 1, 2015 at 0:12

BurninLeoBurninLeo

4,0503 gold badges36 silver badges52 bronze badges

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!

Replace one value in array php

Joshua

4,5592 gold badges28 silver badges43 bronze badges

answered Dec 29, 2011 at 14:13

Replace one value in array php

Prasad RajapakshaPrasad Rajapaksha

5,99410 gold badges35 silver badges51 bronze badges

0

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

answered Mar 11, 2019 at 14:26

Replace one value in array php

2

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.

answered Sep 5, 2016 at 19:50

Replace one value in array php

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);

answered Sep 13, 2016 at 14:27

user3396065user3396065

5205 silver badges15 bronze badges

Based on Deept Raghav's answer, I created the follow solution that does regular expression search.

$arr = [
    'Array Element 1',
    'Array Element 2',
    'Replace Me',
    'Array Element 4',
];

$arr = array_replace(
    $arr,
    array_fill_keys(
        array_keys(
            preg_grep('/^Replace/', $arr)
        ),
        'Array Element 3'
    )
);

echo '
', var_export($arr), '
';

PhpFiddle: http://phpfiddle.org/lite/code/un7u-j1pt

answered Mar 4, 2016 at 22:45

PHP 8, a strict version to replace one string value into another:

array_map(static fn (string $value): string => $value === $find ? $replace : $value, $array); 

An example - replace value foo by bar:

array_map(static fn (string $value): string => $value === 'foo' ? 'bar' : $value, $array);

answered Aug 9, 2021 at 20:38

1

 $green_key = array_search('green', $input); // returns the first key whose value is 'green'

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

answered Dec 29, 2011 at 14:17

Muthu KrishnanMuthu Krishnan

1,6662 gold badges10 silver badges15 bronze badges

1

How do you replace values in an array?

To replace an element in an array: Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.

How to edit array value in PHP?

In some scenarios, you may need or be required to update the values of multiple array elements all at once. To do that, you will need to use the array_replace() function. The array_replace() is an in-built PHP function that replaces the values of an array with values of another array having the same keys or indices.

How to replace array keys in PHP?

function replace_key($arr, $oldkey, $newkey) {.
if(array_key_exists( $oldkey, $arr)) {.
$keys = array_keys($arr);.
$keys[array_search($oldkey, $keys)] = $newkey;.
return array_combine($keys, $arr);.

How do I change the index of an array element in PHP?

We will use array_values() function to get all the values of the array and range() function to create an array of elements which we want to use as new keys or new index of the array (reindexing). Then the array_combine() function will combine both the array as keys and values.