Skip to content

Instantly share code, notes, and snippets.

@subins2000
Created September 8, 2017 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subins2000/bcc7a53d63ee29f85c04c5ef1ff49259 to your computer and use it in GitHub Desktop.
Save subins2000/bcc7a53d63ee29f85c04c5ef1ff49259 to your computer and use it in GitHub Desktop.
Caesar cipher
<?php
/**
* @author Subin Siby <subinsb.com>
*/
function getInput()
{
return trim(fgets(STDIN));
}
function encrypt($i, $k)
{
$s = str_split('abcdefghijklmnopqrstuvwxyz');
$n = '';
foreach (str_split($i) as $l) {
if (!ctype_alpha($l)) {
$n .= $l;
continue;
}
$charPos = array_search(strtolower($l), $s) + $k;
$encChar = $s[($charPos > 25 ? $charPos - 26 : $charPos)];
if (ctype_upper($l)) {
$n .= strtoupper($encChar);
} else {
$n .= $encChar;
}
}
return $n;
}
echo 'Enter string to encrypt:' . PHP_EOL;
$i = getInput();
echo 'Enter key:' . PHP_EOL;
$k = getInput();
echo 'Your encrypted string:' . PHP_EOL . encrypt($i, $k) . PHP_EOL;
@subins2000
Copy link
Author

Try it out : https://eval.in/857751

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment