Create search => replacement array by key intersection

Viewed 66

I have this simple PHP code:

<?php

    $string = "M - T - A - C - B - N - Z.";

    $arrayOne  = ["A", "B", "C", "D"];
    $arrayTwo  = ["D", "E", "F", "G"];


    $length = count($arrayOne);
    for ($i = 0; $i < $length; $i++){
        $replacement[$arrayOne[$i]] = $arrayTwo[$i];
    }

    echo strtr($string, $replacement);

?>

Here I just use the numerical index from both arrays to create a replacement array, which I can use in strtr().

$replacement = [
    "A" => "D",
    "B" => "E",
    "C" => "F",
    "D" => "G",
];

Now I want to do the same thing, just only for the values where the two arrays have the same keys.

So if I have:

$k_1  = [ 
    "hat" => "M",
    "new" => "A",
    "bad" => "B",
    "hot" => "C",
    "big" => "D"    
];


$k_2  = [
    "new" => "D",
    "bad" => "E",
    "hot" => "F",
    "err" => "K",
    "big" => "G"
];

We get the following intersection by keys from the two arrays:

[
    "new",
    "bad",
    "hot",
    "big",
] 

Now I want to use again the values from the first array with these keys as search and the second array values as replacement, e.g.

$replacement = [
    "A" => "D",
    "B" => "E",
    "C" => "F",
    "D" => "G",
];

How do I need to modify my code now, that it will do it like this?

1 Answers
Related