2

For some odd reason, below function returns 11 when input 2, where I would expect it to return 1. What is wrong?

<?php 
function convert($v){

  $arr = array(
    2 => 1,
    21 => 1,

    3 => 2,
    6 => 2,
    11 => 2,
    12 => 2,

    4 => 3,
    14 => 3,
    19 => 3,

    9 => 5,

    1 => 11,
    10 => 11,

    22 => 12,
    23 => 13,
    14 => 14,
    );

  $ret = str_replace(array_keys($arr), array_values($arr), $v);
  return $ret;

}

echo convert(2); // echoes 11

?>

2 Answers 2

3

You're using the wrong function, try strtr instead:

function convert($v){

  $arr = array(
    2 => 1,
    21 => 1,
    ...
    23 => 13,
    14 => 14,
    );

  $ret = strtr($v, $arr);
  return $ret;

}

And in any case: If you find something strange with a PHP function, visit it's manual page and read it, for str_replace a specific example is given that explains your problem: Example #2 Examples of potential str_replace() gotchas

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome, I think every PHP programmer did this mistake once ;)
3

This is because str_replace() processes each replacement from left to right. So when it matches on the key 2 in your array, it is changed to a 1. After that, it hits the key 1 and is changed to an 11. As a short example:

function convert($v) {

    $arr = array(
        1 => 2,
        2 => 3,
        3 => 'cat',
    );

    $ret = str_replace(array_keys($arr), array_values($arr), $v);
    return $ret;
}

echo convert(1); //cat is echoed

So in this case the 1 goes to a 2, then that 2 to a 3, and finally the 3 to cat.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.