Using PHP array functions:
$values = array_intersect($colors, $word);
$flip = array_flip($colors);
$flipValues = array_intersect($flip, $word);
$keys = array_flip($flipValues);
$result = array_merge($values, $keys);
Taking this apart:
- $values = array_intersect($colors, $word);
creates an array with all of the members of $colors whose value is the same as a value in $word, i.e.
$values = array(
"re"=>"red",
"gr" =>"green"
);
2. $flip = array_flip($colors);
This flips the keys and values of $colors, so it is:
$flip = array( "red" => "re",
"orange" => "or",
"black" => "bc",
"brown" => "br",
"green" => "gr"
);
- $flipValues = array_intersect($flip, $word);
This uses array_intersect again, but on the keys (which are the values in $flip). So this will be
$flip = array( "orange" => "or",
"green" => "gr"
);
4. $keys = array_flip($flipValues);
This flips the results back again:
$keys= array( "or" => "orange",
"gr" => "green"
);
Then array_merge combines $values and $keys eliminating duplicates.