How can the use of arrays and loops in PHP scripts enhance the efficiency of Caesar encryption and decryption processes?
Using arrays and loops in PHP scripts can enhance the efficiency of Caesar encryption and decryption processes by allowing for a more streamlined and automated approach to shifting characters. By storing the alphabet in an array and iterating through it using a loop, we can easily shift characters based on the specified key. This eliminates the need for manual character comparisons and calculations, making the encryption and decryption processes more efficient.
function caesarEncrypt($text, $key) {
$alphabet = range('A', 'Z');
$result = '';
foreach(str_split($text) as $char) {
if(in_array(strtoupper($char), $alphabet)) {
$index = array_search(strtoupper($char), $alphabet);
$shifted = ($index + $key) % 26;
$result .= $alphabet[$shifted];
} else {
$result .= $char;
}
}
return $result;
}
function caesarDecrypt($text, $key) {
return caesarEncrypt($text, 26 - $key);
}
$text = "HELLO";
$key = 3;
$encryptedText = caesarEncrypt($text, $key);
$decryptedText = caesarDecrypt($encryptedText, $key);
echo "Original Text: $text\n";
echo "Encrypted Text: $encryptedText\n";
echo "Decrypted Text: $decryptedText\n";
Keywords
Related Questions
- How has the evolution of CSS impacted the way PHP developers handle design elements within their code?
- Are there any potential pitfalls to be aware of when using PHP to determine image sizes?
- What are the advantages and disadvantages of using a Cronjob to update data in a MySQL database compared to real-time API calls in PHP?