How to Use strtr() Function in PHP 8.1 and 8.2 with Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

Hello Friends Today, through this tutorial, I will tell you How to Use `strtr()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP, the `strtr()` function is used to translate characters or replace substrings in a string. It takes three parameters:

1. The input string.
2. The translation table, which specifies what characters or substrings to replace and what to replace them with.
3. Optionally, a third parameter specifying a character or substring limit.

Here’s the syntax of the `strtr()` function:

<?php
strtr(string $string, array|string $replacePairs): string|false
?>

In PHP 8.1 and 8.2, the `strtr()` function has been deprecated in favor of `str_replace()` and `strtr()` now emits a deprecation warning. However, it still functions as expected.

Here’s how you can use `strtr()` function with an example:

<?php
// Define the translation table
$translationTable = array(
'a' => '1',
'b' => '2',
'c' => '3',
);

// Input string
$inputString = 'abc';

// Using strtr() function to translate characters
$outputString = strtr($inputString, $translationTable);

// Output
echo $outputString; 

// Output will be '123'

?>

In this example, the `strtr()` function replaces ‘a’ with ‘1’, ‘b’ with ‘2’, and ‘c’ with ‘3’ in the input string ‘abc’, resulting in ‘123’ as the output.

Remember, although `strtr()` is still available in PHP 8.1 and 8.2, it’s deprecated, and it’s recommended to use `str_replace()` or other appropriate functions instead, especially for new code, to ensure compatibility and maintainability in the future.