How to replace array values according to a value replace map in PHP? -


assume have array:

$origin = ['value1', 'value2', 'value3', 'value4']; 

and replace map array:

$replace_map = [     'value1' => 'replace1',     'value2' => 'replace2',     'value8' => 'replace8', ]; 

i want replace $origin array , expect result be:

$result = myreplace($origin, $replace_map);  $result = ['replace1', 'replace2', 'value3', 'value4']; 

i can loop $origin , each items lookup $replace_map array_key_exists, , replace value in $replace_map,

but think not best way, sounds not efficient.

is there better way this?

further more, if origin values integers, negative, keys in map array positive,

like:

$origin = [-12345, 23456]; $map = [12345 => 98765]; 

also need change -12345 -98765.

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

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -