Morse Code encoder/decoder

pradeep's Avatar author of Morse Code encoder/decoder
This is an article on Morse Code encoder/decoder in PHP.
Morse code is a method for transmitting information, using standardized sequences of short and long elements, for the letters, numerals, punctuation and special characters of a message. The short and long elements can be formed by sounds, marks or pulses, and are commonly known as "dots" and "dashes" or "dits" and "dahs". There are short spaces between the dits and dahs within a character, longer ones between characters, and still longer ones between words.

Read more here

PHP Code:
$lettertomorse=array(
     
"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" => "-----",
     
" " => "   ",
     
"." => ".-.-.-",
     
"," => "--..--",
     
"EOM" => ".-.-."
     
);
 
 
$morsetoletter=array();
 
reset($lettertomorse);
 foreach(
$lettertomorse as $letter => $code
 {
     
$morsetoletter[$code]=$letter;
 }
 
 function 
morse_encode($txt
 {
     global 
$lettertomorse;
 
     
$line="";
     for (
$i=0;$i<strlen($txt);$i++) 
     {
         
$letter=substr($txt,$i,1);
 
         
// ignore unknown characters
         
if (empty($lettertomorse[$letter])) 
             continue;
 
         
$line.=$lettertomorse[$letter]." ";
     }
     return 
$line;
 }
 
 function 
morse_decode($string
 {
     global 
$morsetoletter;
 
     
$line="";
     
$letters=array();
     
$letters=explode(" ",$string);
     foreach (
$letters as $letter
     {
         
// ignore unknown characters
         
if (empty($letter)) 
             
$line.=" ";
         if (empty(
$morsetoletter[$letter])) 
             continue;
 
         
$line.=$morsetoletter[$letter];
     }
     return 
$line;
 } 
Example usage:
PHP Code:
print morse_encode("I Am Fine");