Pedro
Pedro

Reputation: 89

How does the str_replace function work?

I'm trying to understand the str_replace function.

Code:

$a = array(1,8,7,5);
$b = array(3,7,11,6);
$str = '879';
$c = str_replace($a, $b , $str);
echo $c;

Output:

11119

I don't understand the output. Can someone explain how the str_replace function works?

Upvotes: 1

Views: 403

Answers (2)

u_mulder
u_mulder

Reputation: 54831

str_replace replaces pair of values from provided arrays $a, $b. And does it in order, so str_replace($a, $b , $str) means:

replace 1 to 3,
then replace 8 to 7,
then replace 7 to 11
and finally replace 5 to 6.

So, let's go:

  • input 879, replace 1 to 3, output 879
  • input 879, replace 8 to 7, output 779
  • input 779, replace 7 to 11, output 11119
  • input 11119, replace 5 to 6, output 11119

Upvotes: 1

Raphaël Vigée
Raphaël Vigée

Reputation: 2045

Pretty simple, you have 879 :

  1. 8 => 7

So you have now 779

  1. 7 => 11

Now you have 11119

You didn't provided any replacement for 9 or 11 so your returned number is 11119

Upvotes: 1

Related Questions