I am writing a basic morse code converter in PHP which can take a string and convert it into morse code. It is using an associative array, a foreach loop, and a for loop. It works, except for some reason it outputs the morse code equivalent for '0' after each converted character. I can't figure out where the 0 is coming from. If I remove 0 from the associative array, there is no problem but I want to be able to convert numbers as well. If anyone is able to give me some feedback, that would be much appreciated.
Here is the code:
<?php
$string = "dog";
$string_lower = strtolower($string);
$assoc_array = 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"=>"--..",
"0"=>"-----",
"1"=>".----",
"2"=>"..---",
"3"=>"...--",
"4"=>"....-",
"5"=>".....",
"6"=>"-....",
"7"=>"--...",
"8"=>"---..",
"9"=>"----.",
"."=>".-.-.-",
","=>"--..--",
"?"=>"..--..",
"/"=>"-..-.",
" "=>" ");
for($i=0;$i<strlen($string_lower);$i++){
foreach($assoc_array as $letter => $code){
if($letter == $string_lower[$i]){
echo "$code<br/>";
}
}
}
?>