strtr() Does Only One Pass

<?php

$map = [
    'foo' => 'bar',
    'foobar' => 'foo',
];

$input = 'foobar and foo';

echo str_replace(array_keys($map), array_values($map), $input);
// Output: 'bar bar and bar'

echo strtr($input, $map);
// Output: 'baz and bar'

strtr() replaces string inside a string, just like str_replace().

The two functions work both with string and arrays of strings as argument, so it is convenient when you need to replace several distinct and non-overlapping strings.

In terms of readability, strtr() accepts a hash with original => replacement strings, while str_replace() needs them split and aligned.

Finally, strtr() only does one pass on the string, and replaces the longest available string. No need to sort the original strings by size, or end up with the replaced string used multiple times. It is actually more efficient and more predictable.

See Also

PHP Features

Last updated: 16 July 2026