How can loops and mathematical operations be utilized in PHP to shift characters in a Caesar cipher-like encryption?

To shift characters in a Caesar cipher-like encryption using PHP, we can utilize loops and mathematical operations to shift each character by a specified number of positions. We can achieve this by converting each character to its ASCII value, applying the shift operation, and then converting it back to a character. By looping through each character in the input string and performing these operations, we can create a simple encryption algorithm.

function caesarCipher($input, $shift) {
    $output = "";
    $length = strlen($input);
    
    for ($i = 0; $i < $length; $i++) {
        $char = $input[$i];
        
        if (ctype_alpha($char)) {
            $ascii = ord($char);
            $shiftedAscii = $ascii + $shift;
            
            if (ctype_upper($char)) {
                $output .= chr(($shiftedAscii - 65) % 26 + 65);
            } else {
                $output .= chr(($shiftedAscii - 97) % 26 + 97);
            }
        } else {
            $output .= $char;
        }
    }
    
    return $output;
}

$input = "Hello, World!";
$shift = 3;
$encrypted = caesarCipher($input, $shift);
echo $encrypted;