The story of one typo or strtr() replacing wrong characters

  1. Comments (1)

Recently there was a question on Russian Stack Overflow, from a guy claiming that strtr() works incorrectly. They even provided some proof-codes:

$value 'B1000';   // here we have zeros
$converter = array('-'''); // delete all dashes
$tr strtr($value$converter);  
echo 
$tr;   // outputs 'B1111' - all 0s got replaced with 1s

another example:

$value 'B1000';   // we have zeros
$converter = array('-''_'); // replace all dashes to underscores
$tr strtr($value$converter);  
echo 
$tr;   // outputs 'B1' - all zeros are gone

Although this problem was caused by a simple typo, I found it rather amusing, given the unexpected results, and I felt that it could be an interesting example showing how the type juggling works in PHP. Let's see:

So now you can tell that replacements went according to the following rules

and naturally, we just got 0s replaced to 1s as well as 0s removed!

It is worth to mention that such a case is also a good example as to why debugging is so important. The essential part of debugging process is called tracing which stands for running our program line by line, checking all the intermediate values. Tracing a code with a good IDE is fun, but of course one could always do it manually. In the present case it's just takes adding a debugging output for the replacement array (i.e. var_dump($converter)) to make one see the real cause and to make them stop blaming the honest function of strtr()!


Related articles: