0

I have made my own array with all the letters, numbers and most of the symbols and given each one a number for exemple 'a' = 19; How do I replace the $string letters/numbers with the numbers in the array so that $newString = 19202122 for example?

$string = 'abcd'; $stringList = array( 19 => 'a', 20 => 'b', 21 => 'c', 22 => 'd', }; $newString = 19202122; 
3
  • 1
    Have you tried anything? Commented Nov 14, 2013 at 20:59
  • You should flip your array around, 'a' => 19 and so on. Commented Nov 14, 2013 at 21:00
  • I'm really bad at php and trying to learn, I have been looking how to do it but I could not find anyting... Commented Nov 14, 2013 at 21:02

3 Answers 3

2

You can use the functions str_replace, array_keys and array_values. Like that:

$string = 'abcd'; $stringList = array( 19 => 'a', 20 => 'b', 21 => 'c', 22 => 'd', }; $newString = str_replace(array_values($stringList), array_keys($stringList), $string); echo $newString; // 19202122 
Sign up to request clarification or add additional context in comments.

5 Comments

It would be more readable and also more efficient, if the array was not defined in the style of replacement => needle. See my comment for an example
@MartinCernac Well you are right but I wanted to keep the author's array, we don't know how and from where he got it.
Well he mentioned, that "he made his own array" so I based my answer on that. Anyway your solution is clearly easier to implement, since it's a drop-in.
how can I make it in a more efficient way?
@Michael check my answer. It is more efficient, because it doesn't have to modify the array, it just uses it as you define it.
1

Define the array the other way and use the strtr() function like this:

$string = 'abcd'; $stringList = array( 'a' => 19, 'b' => 20, 'c' => 21, 'd' => 22, ); $newString = strtr($string, $stringList); 

Comments

1

Use str_replace with arrays:

$letters = array('a','b','c','d'); $numbers = array(19,20,21,22); $newString = str_replace($letters,$numbers,$string); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.