How to check if two strings are isomorphic in PHP

2 Answers

0 votes
// Two strings are isomorphic if characters in one can be replaced to get the other, 
// while preserving the order.

function areIsomorphic(string $s, string $t): bool {
    if (strlen($s) !== strlen($t)) {
        return false;
    }

    $mapST = [];
    $mapTS = [];

    for ($i = 0; $i < strlen($s); $i++) {
        $c1 = $s[$i];
        $c2 = $t[$i];

        // Check mapping from s → t
        if (isset($mapST[$c1])) {
            if ($mapST[$c1] !== $c2) {
                return false;
            }
        } else {
            $mapST[$c1] = $c2;
        }

        // Check mapping from t → s
        if (isset($mapTS[$c2])) {
            if ($mapTS[$c2] !== $c1) {
                return false;
            }
        } else {
            $mapTS[$c2] = $c1;
        }
    }

    return true;
}

var_dump(areIsomorphic("egg", "add"));     
var_dump(areIsomorphic("foo", "bar"));     
var_dump(areIsomorphic("paper", "title")); 



/*
run:

bool(true)
bool(false)
bool(true)

*/

 



answered Dec 19, 2025 by avibootz
0 votes
// Two strings are isomorphic if characters in one can be replaced to get the other, 
// while preserving the order.

function areIsomorphic(string $s, string $t): bool { 
    return array_map('strpos', array_fill(0, strlen($s), $s), str_split($s)) === 
           array_map('strpos', array_fill(0, strlen($t), $t), str_split($t)); 
}

var_dump(areIsomorphic("egg", "add"));     
var_dump(areIsomorphic("foo", "bar"));     
var_dump(areIsomorphic("paper", "title")); 



/*
run:

bool(true)
bool(false)
bool(true)

*/

 



answered Dec 19, 2025 by avibootz
...