How can I replace the values ββof an array according to the value replacing the map in PHP?
Suppose I have an array:
$origin = ['value1', 'value2', 'value3', 'value4'];
and replace the array of cards:
$replace_map = [
'value1' => 'replace1',
'value2' => 'replace2',
'value8' => 'replace8',
];
I want to replace an array $origin
and expect the result to be:
$result = myReplace($origin, $replace_map);
$result = ['replace1', 'replace2', 'value3', 'value4'];
I can loop through $origin
and for each search for elements $replace_map
by array_key_exists
and replace it with value in $replace_map
,
But I think this is not the best way, it sounds inefficient.
Is there a better way to do this?
Also, if the start values ββare integers, but some are negative, but the keys in the card array are all positive,
like:
$origin = [-12345, 23456];
$map = [12345 => 98765];
also needs to be changed -12345
to -98765
.
source to share
$origin = ['value1', 'value2', 'value3', '-2'];
$replace_map = [
'value1' => 'replace1',
'value2' => 'replace2',
'value8' => 'replace8',
2 => 77
];
$new = array_map(function($i) use($replace_map) {
return preg_replace_callback('/^(-)*(.+)$/',
function($m) use($replace_map) {
if(!isset($replace_map[$m[2]]))
return($m[0]);
return $m[1] . $replace_map[$m[2]];
},$i);
}, $origin);
print_r($new);
Result
Array
(
[0] => replace1
[1] => replace2
[2] => value3
[3] => -77
)
source to share
str_replace can process arrays to find and replace parameters.
Try this code:
<?php
$origin = ['value1', 'value2', 'value3', 'value4'];
print_r($origin);
$search = ['value1', 'value2', 'value8'];
$replace = ['replace1', 'replace2', 'replace8'];
$result = str_replace($search, $replace, $origin);
print_r($result);
Output signal
Array
(
[0] => value1
[1] => value2
[2] => value3
[3] => value4
)
Array
(
[0] => replace1
[1] => replace2
[2] => value3
[3] => value4
)
In addition, str_replace treats as items as strings, so integers will be replaced as well. Partial matches will also be replaced, for example:
echo str_replace(2, 5, -200);
will result in -500.
source to share
You can use array_map to trigger str_replace for each of the array values, for example:
$origin = ['value1', 'value2', 'value3', 'value4'];
$result = array_map('myReplace', $origin);
echo '<pre>' . print_r($result, true) . '</pre>';
function myReplace($value) {
$replace_map = [
'value1' => 'replace1',
'value2' => 'replace2',
'value8' => 'replace8',
];
return str_replace(array_keys($replace_map), array_values($replace_map), $value);
}
Or for newer PHP versions, you can use the anonymous function
$replace_map = [
'value1' => 'replace1',
'value2' => 'replace2',
'value8' => 'replace8',
];
$origin = ['value1', 'value2', 'value3', 'value4'];
$result = array_map(function($value) use ($replace_map) {
return str_replace(array_keys($replace_map), array_values($replace_map), $value);
}, $origin);
echo '<pre>' . print_r($result, true) . '</pre>';
source to share