My string of numbers are not replacing correctly.
I am expecting the output after replacing to be 9876543210 but it doesnt seem to be the case.
What am i doing wrong?
<?php
$numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$code = array('9', '8', '7', '6', '5', '4', '3', '2', '1', '0');
$pre = '0123456789';
echo $pre . " ==> " . str_replace($numbers, $code, $pre);
?>
That produces the output 0123443210 because str_replace with an array will start replacing earlier matches as it iterates over $numbers
For a single letter transposition like this, use strtr instead
$encoded = strtr($pre, "0123456789", "9876543210");
It's a bit long to explain but let me show you what's happening. For each element in the array it's replacing everything from the start from the string. Let's define N for $number and C for $code and R for $result
N C R
0 9 9123456789
1 8 9823456789
2 7 9873456789
3 6 9876456789
4 5 9876556789
5 4 9876446789
6 3 9873443789
7 2 9823443289
8 1 9123443219
9 0 0123443210
Thus you should use the solution provided by Paul using strtr()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With