➤ Convert text to Morse code.
// The array contains only numbers and alphabets.
$morse = [
"A" => ".-","B" => "-...","C" => "-.-.","D" => "-..",
"E" => ".","F" => "..-.","G" => "--.","H" => "....",
"I" => "..","J" => ".---","K" => "-.-","L" => ".-..",
"M" => "--","N" => "-.","O" => "---","P" => ".--.",
"Q" => "--.-","R" => ".-.","S" => "...","T" => "-",
"U" => "..-","V" => "...-","W" => ".--","X" => "-..-",
"Y" => "-.--","Z" => "--..",1 => ".----",2 => "..---",
3 => "...--",4 => "....-",5 => ".....",6 => "-....",
7 => "--...",8 => "---..",9 => "----.",0 => "-----",
];
function convert_text_to_morse($str){
global $morse;
$result = "";
for ( $i = 0; $i < strlen($str); $i++ ){
if( $str[$i] == " " ) $result .= " / ";
else {
$result .= $morse[strtoupper($str[$i])]." ";
}
}
return $result;
}
// print_r ($morse);
echo convert_text_to_morse("Hello world");
// outputs: .... . .-.. .-.. --- / .-- --- .-. .-.. -..
echo "\n";
echo convert_text_to_morse("404 ERROR");
// outputs : ....- ----- ....- / . .-. .-. --- .-.