How to use XOR to swap two characters in a string in PHP

1 Answer

0 votes
declare(strict_types=1);

/**
 * Swaps two characters in a string in-place using the XOR swap algorithm.
 *
 * This function demonstrates bitwise XOR swapping for educational purposes.
 * In production code, standard temporary variables or PHP array destructuring
 * (e.g., [$text[$left], $text[$right]] = [$text[$right], $text[$left]]) are preferred.
 *
 * @param string $text  String passed by reference containing characters to swap.
 * @param int    $left  Zero-based index of the first character.
 * @param int    $right Zero-based index of the second character.
 */
function xorSwapCharacters(string &$text, int $left, int $right): void
{
    $length = strlen($text);

    // Bounds checking, negative index handling, and empty check
    if ($length === 0 || $left < 0 || $left >= $length || $right < 0 || $right >= $length) {
        return;
    }

    // XOR swap fails if $left === $right because ($x ^ $x) evaluates to 0
    if ($left === $right) {
        return;
    }

    // Convert chars to ASCII integers, perform XOR, and assign back
    $text[$left]  = chr(ord($text[$left]) ^ ord($text[$right]));
    $text[$right] = chr(ord($text[$right]) ^ ord($text[$left]));
    $text[$left]  = chr(ord($text[$left]) ^ ord($text[$right]));
}

// Example usage
$text = "hello";

echo "Before: " . $text . PHP_EOL;

xorSwapCharacters($text, 1, 4);

echo "After:  " . $text . PHP_EOL;



/*
Run:

Before: hello
After:  holle

*/

 



answered Sep 30 by avibootz
...