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.
The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.
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.
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.
The array_keys() function returns an array containing the keys.
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.
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With