Richard
Richard

Reputation: 4415

str_replace with array_keys/array_values returns strange result

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

?>

Upvotes: 2

Views: 1656

Answers (2)

hakre
hakre

Reputation: 197599

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

Upvotes: 3

jprofitt
jprofitt

Reputation: 10964

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.

Upvotes: 3

Related Questions