Here, I suppose, you have all your pairs in an array. For example, for your example, you call analogsOf(array(array("a1", "abcd"), array("a2", "a3"), array("a3", "a1")), "abcd").
, , , , , , . , , .
function analogsOf(array $pairs, $key) {
$res = array($key);
$i = 0;
$changed = false;
while ($i < count($pairs)) {
$current = $pairs[$i];
foreach ($res as $item) {
if (($current[0] === $item) && (!in_array($current[1], $res)) {
$res[] = $current[1];
$i = 0;
}
else if (($current[1] === $item) && (!in_array($current[0], $res)) {
$res[] = $current[0];
$i = 0;
}
else {
$i++;
}
}
}
return $res;
}
, , , . , , , , , , , , .