1

I want to merge two arrays and replace the text with strtr function.

I was using this before

$text = "cat cow";
$array = array(
"cat" => "dog",
"cow" => "bull"
);
$output = strtr($text, $array);

this returned dog bull...

Now I have two arrays like this...

$a = array("cat", "dog");
$b = array("dog", "bull");

Both the arrays will have values to replace

Now, how do I combine them and replace? I tried $array = $a + $b and array_combine, but they didn't work...

Please Help...

Shahbaz Singh
  • 191
  • 1
  • 9
  • Possible duplicate: http://stackoverflow.com/questions/4137140/merge-2-arrays-with-no-duplicated-keys – Tim Jun 18 '12 at 13:34
  • `strtr()` returns a string so you would have two arrays. – Bailey Parker Jun 18 '12 at 13:36
  • Can you update the question with an example of what you want the "combined" array to look like? – Eric H Jun 18 '12 at 13:38
  • possible duplicate of [PHP merge array(s) and delete double values](http://stackoverflow.com/questions/6180090/php-merge-arrays-and-delete-double-values) – Bailey Parker Jun 18 '12 at 13:38
  • if `$a` contains *keys* and `$b` contains *values*, then `$c = array_combine($a, $b);` - `$c` will have *replace pairs* for `strtr` – poncha Jun 18 '12 at 13:40

3 Answers3

4

I think two arrays must be

$a = array("cat", "cow");
$b = array("dog", "bull");

And you can use

$c = array_combine($a, $b);
$output = strtr($text, $c);
Simon
  • 86
  • 2
3

I dont know how you have tried.

$text = "cat cow";
$array = array(
"cat" => "dog",
"cow" => "bull"
);

$text = "cat cow";

$array = array("cat" => "dog",
"cow" => "bull"
);
$output = strtr($array, $array);
echo $output;
//output -> dog bull


$a = array("cat", "cow");
$b = array("dog", "bull");
$c = array_combine($a,$b);
print_r($c);
$output1 = strtr($text, $c);
echo $output1;
//output -> dog bull

I thing the above code gives you what output you need.

I think you have used the wrong array Check the $a and $b array I hope i have helped you.

Shaik Baba
  • 112
  • 2
1

Do you mean merge them to get array('cat','dog','bull')? If so just do:

$array = array_unique(array_merge($a,$b));
EmmanuelG
  • 1,051
  • 9
  • 14
  • Could someone explain why the -1? The question is/was somewhat ambiguous and this could very well have been a correct answer. – Eric H Jun 18 '12 at 13:54
  • 1
    Indeed I believe I misunderstood the question entirely. Rather than back out and delete this, I'll leave it here in case anyone accidentally reads this and it helps them. Either way, thanks for requesting an explanation @EricH. – EmmanuelG Jun 18 '12 at 13:57
  • 1
    No problem. I went ahead and +1'd your answer as I found it useful. – Eric H Jun 18 '12 at 15:31