Saturday, February 28, 2009

Phonetic Alphabet

It seems to me that most people have trouble remembering the phonetic alphabet (probably myself included). Unless you're a pilot or air traffic controller, it's unlikely that your job requires you to have it memorized. People get by with whatever word comes to mind ("A as in Adam"), but this seems like an opportunity to write some code.


For maximum reusability, I'm going to write my function to convert individual characters at a time. Looping through the characters of the string will occur outside the function. The function is too long to paste here in its entirety, but it will be posted on Snipplr and linked at the bottom of this entry.


PHP has key/value arrays where we can specify any keys we want, so we'll declare an array containing all the conversions and use the input to retrieve the correct string from the array. ASP's arrays don't have this flexibility; we could achieve this with a Dictionary scripting object, but I'm concerned about the overhead associated with that. I'm going to use a Select...Case statement (AKA switch statement), but there is a chance that this is actually not any better. I'll leave the determination of this as an exercise to the reader. Also left as an exercise to the reader is the writing of the looping code.


2 comments:

Unknown said...

u write: "Looping through the characters of the string will occur outside the function." - can you post any short example code that will work? cant get it done. thanks!!

Scott said...

<?php
$string = "string";
$array = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
foreach($array as $char)
{
print(phonetic($char)."<br/>");
}
?>
This outputs:
sierra
tango
romeo
india
november
golf