php str_replace

i'm using this code to make simple encryption:

    function idEncrypt($string)
{
    $multiply = 2457;
    $original = array('1', '2','3', '4', '5', '6', '7', '8', '9', '0');
    $replace = array('6', '3', '9', '1', '2', '8', '5', '0', '4', '7');
    $idEncrypt = str_replace($original, $replace, $string);
    //$idEncrypt = $idEncrypt * $multiply;
    return $idEncrypt;      
}

it is supposed to take a number, and replace it with the right number from $replace array. i'm inputting "234", and got "441" for an answer, where i supposed to get "391".
any suggestions ?

The problem is that str_replace is being applied over and over, for each element in the array.

For '234', first 2 is being replaced with 3, and then 3 is being replaced with 9, and then 9 is being replaced with 4.

The 3 is being replaced with 9, and then the 9 is replaced with 4.

Finally, the 4 is being replaced with 1, creating '441'.

The important bit is found in the docs of the str_replace function:

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

For your simple "encryption", you want to use PHP's strtr function:

function transform($string) {
  $original = '1234567890';
  $replace = '6391285047';
  return str_replace($string, $original, $replace);
}

nb. Please don't cook your own "encryption" functions. Use established, well-tested algorithms and libraries.

Try using strtr instead. You'll need to change your code to have:

$original = "1234567890";
$replace = "6391285047";

And that's get around the gotcha of str_replace.