简体   繁体   中英

PHP array elements replace

I want to make some encryption and write numbers
I used:

$a = [100,101,102,103,104,105]
function decrition (array $a){
return preg_replace('/101/','a',$a);
}

And it's returns me all letters "a" for each 101 in array. How can I change next? 101 to "b", 102 to "c" etc.

 return preg_replace('[101|102|103|104|105]','a',$a);

this method replace all this numbers to letter "a"

return preg_replace('[101|102|103|104|105','a|b|c|d|e',$a);

unfortunately it's not working

Why do you try to treat it as a string?

<?php

$a = [ 101, 102, 103 ];

$replace_array = array(101 => "a", 102 => "b");
$b = array_map(function($val) use ($replace_array) {
  return (isset($replace_array[$val]) ? $replace_array[$val] : $val);
}, $a);

var_dump($a, $b);

Gives the following output:

array(3) {
  [0]=>
  int(101)
  [1]=>
  int(102)
  [2]=>
  int(103)
}
array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  int(103)
}

Maybe you are looking for something like this?

$test = str_replace($a, array('a','b','c','d','e','f'), $a);
print_r($test);

此解决方案有效

 return str_replace(['101', '102', '103', '104', '105'], ['a', 'b', 'c', 'd', 'e'], $a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM