Skip to content

Commit

Permalink
Add morse code encoding/decoding for PHP
Browse files Browse the repository at this point in the history
Add PHP implementation for morse code encoding/decoding.
  • Loading branch information
raphaelz committed Oct 2, 2018
1 parent 3151797 commit ba5515b
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions code/string-algorithms/morse-code/morsecode.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/* Part of Cosmos by OpenGenus Foundation */

/* Example Usage:
echo morseEncode('HELLO');
echo morseDecode('.... . .-.. .-.. ---');
*/

function morseDecode($str)
{

$toCharMorseMap = ["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"=> "-----"];
$fromMorseMap = array_flip($toCharMorseMap);

$charArray = [];

$chars = explode(' ', strtoupper($str));
foreach ($chars as $char) {
$charArray[] = $fromMorseMap[$char];
}

return implode('', $charArray);

}

function morseEncode($str)
{

$toCharMorseMap = ["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"=> "-----" ];

$chars = str_split(strtoupper($str));
$morseArray = [];

foreach ($chars as $char) {
$morseArray[] = $toCharMorseMap[$char];
}

return implode(' ', $morseArray);
}

0 comments on commit ba5515b

Please sign in to comment.