PHP 8.4.24 Released!

Voting

: min(eight, seven)?
(Example: nine)

The Note You're Voting On

electro at whatever dot com
19 years ago
<?php

/**
 * Rotate each string characters by n positions in ASCII table
 * To encode use positive n, to decode - negative.
 * With n = 13 (ROT13), encode and decode n can be positive.
 * 
 * @param string $string
 * @param integer $n
 * @return string
 */
function rotate($string, $n) {
    
    $length = strlen($string);
    $result = '';
    
    for($i = 0; $i < $length; $i++) {
        $ascii = ord($string{$i});
        
        $rotated = $ascii;
        
        if ($ascii > 64 && $ascii < 91) {
            $rotated += $n;
            $rotated > 90 && $rotated += -90 + 64;
            $rotated < 65 && $rotated += -64 + 90; 
        } elseif ($ascii > 96 && $ascii < 123) {
            $rotated += $n;
            $rotated > 122 && $rotated += -122 + 96;
            $rotated < 97 && $rotated += -96 + 122; 
        }
        
        $result .= chr($rotated);
    }
    
    return $result;
}

$enc = rotate('string', 6);
echo "Encoded: $enc<br/>\n";
echo 'Decoded: ' . rotate($enc, -6);

?>

<< Back to user notes page

To Top