phparraysassociative-arraykey-valuestrtr

Convert two flat, indexed arrays containing two values into an associative array with two elements


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 then array_combine(), but that didn't work.


Solution

  • 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);