Submit Your Article Forum Rules

Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: PHP loops?

  1. #1
    Member
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    64

    PHP loops?

    Hiya guys, I need some help with the following script.... I'm trying to get a code which will tell you the right word to represent each letter of a variable entered into a text box... look at the code below. I've managed to get it to display the first letter, but need some assistance to get the code to loop, onto the second letter and so forth... can anyone help?

    <form method="post">
    <tr align="left">
    <td><label for="text">Enter text: </label></td>
    <td><input name="text" type="text" class="widebox" id="text" /></td>
    </tr>
    </tr>
    <input type="submit" name="Select" title="Phonetify" value="Phonetify"/>
    </form>
    <br /><br />
    <?php
    $var =$_POST['text'];
    echo '<strong>'.$var.'</strong> will become the following phonetically. <br /><br /> ';

    if ($var[0]=='a')
    echo "Alpha<br />";
    elseif ($var[0]=='b')
    echo "Bravo <br />";
    elseif ($var[0]=='C')
    echo "Charlie <br />";
    elseif ($var[0]=='D')
    echo "Delta <br />";
    elseif ($var[0]=='E')
    echo "Echo <br />";
    elseif ($var[0]=='F')
    echo "Foxtrot <br />";
    elseif ($var[0]=='G')
    echo "Golf <br />";
    elseif ($var[0]=='H')
    echo "Hotel <br />";
    elseif ($var[0]=='I')
    echo "India <br />";
    elseif ($var[0]=='J')
    echo "Juliet <br />";
    elseif ($var[0]=='K')
    echo "Kilo <br />";
    elseif ($var[0]=='L')
    echo "Lima <br />";
    elseif ($var[0]=='M')
    echo "Mike <br />";
    elseif ($var[0]=='N')
    echo "November <br />";
    elseif ($var[0]=='O')
    echo "October <br />";
    elseif ($var[0]=='P')
    echo "Papa <br />";
    elseif ($var[0]=='Q')
    echo "Quebec <br />";
    elseif ($var[0]=='R')
    echo "Romeo <br />";
    elseif ($var[0]=='S')
    echo "Sierra <br />";
    elseif ($var[0]=='T')
    echo "Tango <br />";
    elseif ($var[0]=='U')
    echo "Uniform <br />";
    elseif ($var[0]=='V')
    echo "Victor <br />";
    elseif ($var[0]=='W')
    echo "Whisky <br />";
    elseif ($var[0]=='X')
    echo "Xray <br />";
    elseif ($var[0]=='Y')
    echo "Yankee <br />";
    elseif ($var[0]=='Z')
    echo "Zulu <br />";
    ?>
    http://www.dynamicexposure.com - Photography Tutorials, Help and Forum.
    http://tibia.dynamicexposure.com - Tibia game information.
    http://phonetic-code.dynamicexposure.com - Phonetify - Phonetic Code for the words you enter

  2. #2
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,785
    First, create an array containing all your data, using the letters as keys:
    PHP Code:

    $STACK 
    = array(
     
    'A' => 'Alpha',
     
    'B' => 'Bravo',
     
    'C' => 'Charlie',
     
    'D' => 'Delta',
     
    'E' => 'Echo',
     
    'F' => 'Foxtrot',
     
    'G' => 'Golf',
     
    'H' => 'Hotel',
     
    'I' => 'India',
     
    'J' => 'Juliet',
     
    'K' => 'Kilo',
     
    'L' => 'Lima',
     
    'M' => 'Mike',
     
    'N' => 'November',
     
    'O' => 'October',
     
    'P' => 'Papa',
     
    'Q' => 'Quebec',
     
    'R' => 'Romeo',
     
    'S' => 'Sierra',
     
    'T' => 'Tango',
     
    'U' => 'Uniform',
     
    'V' => 'Victor',
     
    'W' => 'Whiskey',
     
    'X' => 'X-ray',
     
    'Y' => 'Yankee',
     
    'Z' => 'Zulu',
    );

    function 
    something() {
    global 
    $STACK;
    $result "";

    // some form of input controlled loop to gather all characters, maybe?

    // Truncate the POST string to only the first alpha character, case insensitive. 

    // regex and replace leading spaces and non-alpha characters with ""

    $var preg_replace("/[^a-z]/i"""$var);

    // first character and force it into uppercase

    $var strtoupper(substr($var01));

    // Now traverse your index for a match and return the callout:

    $result .= alphaToCallout($var) . ", ";

    // get another character, keeping $result alive
    .
    .
    .
    };

    function 
    alphaToCallout($post) {
     global 
    $STACK;
     foreach (
    $STACK as $alpha => $callout) {
      if (
    $post == $key) return $callout;
     };
    }; 
    Not tested, so might need tweaking. Let us know if this helps.
    Last edited by weegillis; 04-06-2012 at 08:01 PM. Reason: tweaks already

  3. #3
    Member
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    64
    I have to be honest with you Gillis, I don't have a clue about what you just typed there, beyond your notes. That being said, here's the challenging part... it doesn't work if I replace what i have with the code you wrote... I get the following

    ( ! ) Parse error: syntax error, unexpected '.' in C:\wamp\www\Phonetify\Copy of index.php on line 117

    The error is appearing in the following section that you've wrote ..

    // get another character, keeping $result alive
    .
    .
    .
    };
    http://www.dynamicexposure.com - Photography Tutorials, Help and Forum.
    http://tibia.dynamicexposure.com - Tibia game information.
    http://phonetic-code.dynamicexposure.com - Phonetify - Phonetic Code for the words you enter

  4. #4
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,785
    The 'function something()' part is not run-able code, but 'thought balloons'. That's why it won't parse. It's not syntactically correct. The big hints would be the open dots representing a vertical ellipses, which are not commented out, and would throw an error in the PHP parser. Also note that the foreach() above is incorrect, I have $key instead of $alpha in the code. Apologies...

    Let's break it down to what is syntactically correct:

    1) the array.
    2) the function, alphaToCallout() (once the correct variables are applied)


    The function, something() is one you would have to sort out depending upon how the input is to be handled:

    a. One character at a time; or,
    b. One word at a time; or,
    c. A complete phrase, including spaces, in which case the filter would need to be modified to include spaces (that are not leading or trailing).


    For situation a., the $_POST['text'] will be truncated to the first alpha character, as above. In this example, we need to assume that the user may send more than one character; ergo, taking the time to pare it down and pound it into the right form:

    PHP Code:
    // submitted POST comes in and is sampled, 'text' being the attribute value in the input form control, name="text".

    $var $_POST['text']

    $var truncSubmit($var);

    if (
    $var) {
     echo 
    alphaToCallout($var);
    } else {
     echo 
    "No alpha character found.";
    }

    // end

    function truncSubmit($post) {
     
    $post preg_replace("/[^a-z]/i"""$post);
     if (!
    $post) return;
     return 
    strtoupper(substr($post01));
    };

    function 
    alphaToCallout($post) {
     global 
    $STACK;
     foreach (
    $STACK as $alpha => $callout) {
      if (
    $post == $alpha) return $callout;
     };
    }; 
    If the user submits, " .* abcde ", the above renders it as "A". We test for NULL in two places, before calling truncSubmit(), and before calling alphaToCallout(). No point running the procedures if there is nothing to work with. This is obviously the simplest and most straight forward.

    It would be a pain for the user to have to submit one letter at a time, and real pain to set up the loop to return to the form, over and over, so if you wish to allow the user to enter a word, or phrase, then some tweaks on the filter will be needed, and you will need a PHP callback function for your AJAX to communicate with if you want real time response as the user types. This is above the scope of this discussion, at present, so we'll stick to one Submit, one word, or one Submit, one phrase and operate on the returned 'text'.

    For a single word, the preg_replace() will need to, a) remove leading spaces; and b) find the first word separator (space) in the event the user submitted a phrase.

    You would then set up a loop, after first distributing all the word letters in an array, parsing through the array one element at a time, and passing the content to alphaToCallout(). This is where the $result variable comes in. We will concatenate each returned callout word to the string, and echo the final $result upon completion of the loop.

    For a phrase, the preg_replace will need to, a) remove leading and trailing spaces; and b) breakout the individual words and store them in an array (perhaps), or simply do as above, pushing the results into an array with one character per element, including the spaces between the words.

    We would need a loop again, minding that "" or " " will return nothing, so we need to catch the spaces, add them to the $result, and jump to the next element.

    Each of these last two conditions makes things a bit more complicated, so I would get the spit and polish on the single character method, first, then move on to making your method smarter (by adding new functions, not modifying the ones you have that work for their scenario).
    Last edited by weegillis; 04-07-2012 at 03:42 PM. Reason: $key -> $alpha - my mistake.

  5. #5
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,785
    The array is not correct... there should not be a comma after 'Zulu'. This will throw an error.

  6. #6
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,785
    Since I opened this up, it might be best to offer a prototype for you to work from. This is a working example in its simplest form.
    PHP Code:
    <?php 
    $STACK 
    = array( 'A' => 'Alpha','B' => 'Bravo','C' => 'Charlie','D' => 'Delta','E' => 'Echo','F' => 'Foxtrot','G' => 'Golf','H' => 'Hotel','I' => 'India','J' => 'Juliet','K' => 'Kilo','L' => 'Lima','M' => 'Mike','N' => 'November','O' => 'October','P' => 'Papa','Q' => 'Quebec','R' => 'Romeo','S' => 'Sierra','T' => 'Tango','U' => 'Uniform','V' => 'Victor','W' => 'Whiskey','X' => 'X-ray','Y' => 'Yankee','Z' => 'Zulu' );
    function 
    truncSubmit($post) {
     
    $post preg_replace("/[^a-z]/i"""$post);
     if (!
    $post) { return NULL; } else { return strtoupper(substr($post01)); };
    };
    function 
    alphaToCallout($post) {
     global 
    $STACK;
     foreach (
    $STACK as $alpha => $callout) {if ($post == $alpha) return $callout; };
    };
    $var = ($_POST['text']) ? $_POST['text'] : NULL;
    if (
    $var) {
     
    $sent truncSubmit($var);
     if (
    $sent) { $result alphaToCallout($sent); } else { $result "No POST data";  };
    } else { 
    $sent "No POST data"; };
     
    ?>
    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>A to Alpha .. Z to Zulu</title>
    <meta name="description" content="a method to generate callouts from alpha characters">
    <style>textarea{display:block}</style>
    </head><body>
    <form method="post" action="index.php">
     <input type="text" name="text" autofocus="autofocus">
     <input type="submit" value="Send">
     <textarea disabled="disabled"><?php echo "Sent: $sent\nResult: $result\n"?></textarea>
    </form></body></html>
    Last edited by weegillis; 04-08-2012 at 12:46 AM. Reason: Error trap installed / tweaking / extraneous removed / textarea disabled / html5 autofocus

  7. #7
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,785

    Post

    As is often the case, I learn more than anyone from these exercises, or am often left to assume as much due to lack of discussion afterward. However, it does give me pleasure to spend a holiday weekend 'not working' but 'working' on something fun and interesting, as this little project turned out to be.

    I hope the OP is able to gain some insight from this, and that he has no intention of repeating this in an assignment (the prof will find it here) without being able to fully explain and document it, if asked. Copy and paste is no way to learn programming of any sort, least of all, PHP scripting. We get the most gains when we dirty our own hands.

    That said, here is the Multi-word Phrase version of the above, single character NATO Phonetic Converter.
    PHP Code:
    <?php /* Multiword Phrase NATO Phonetic Converter by RC Pierce 2012-04-08 */
    $STACK=array('A'=>'Alpha','B'=>'Bravo','C'=>'Charlie','D'=>'Delta','E'=>'Echo','F'=>'Foxtrot','G'=>'Golf','H'=>'Hotel','I'=>'India','J'=>'Juliet','K'=>'Kilo','L'=>'Lima','M'=>'Mike','N'=>'November','O'=>'October','P'=>'Papa','Q'=>'Quebec','R'=>'Romeo','S'=>'Sierra','T'=>'Tango','U'=>'Uniform','V'=>'Victor','W'=>'Whiskey','X'=>'X-ray','Y'=>'Yankee','Z'=>'Zulu');
     
    $NPD "No POST data"
     function 
    postFilter($post) {
      
    $post preg_replace("/^[ ]+|[^a-z ]|^[ ]+$/i"""$post);
      if (!
    $post) return NULL;
      return 
    strtoupper($post);
     }; 
     function 
    postSplit($post) {
      
    $postChars = array();
      
    $postChars preg_split('//'$post, -1PREG_SPLIT_NO_EMPTY);
      return 
    $postChars;
     }; 
     function  
    alphaToPhonetic($post) {
      global 
    $STACK;
      foreach (
    $STACK as $alpha => $phonetic) { if ($post == $alpha) return $phonetic; };
     }; 
     function 
    wordToPhonetic($posts) {
      
    $result "";
      foreach (
    $posts as $index => $letter) { $result .= "\n" alphaToPhonetic($letter); };
      return 
    $result;
     };
     
    $var = ($_POST['text']) ? $_POST['text'] : NULL;
     if (
    $var) {
      
    $sent postFilter($var);
      if (
    $sent) {
       
    $sentChar substr($sent01);
       if (
    $sentChar) { $charResult =  alphaToPhonetic($sentChar); } else { $charResult $NPD; };
       if (
    strlen($sent) > 1) { $charResults wordToPhonetic(postSplit($sent)); } else { $charResults $charResult; };
      } else { 
    $sent $sentChar $NPD; };
     } else { 
    $sent $sentChar $NPD; };
     
    ?>
    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Multiword Phrase NATO Phonetic Alphabet converter</title>
    <style>textarea{width:400px;height:300px}</style></head><body>
    <form method="post" action="index.php">
     <input type="text" name="text" autofocus="autofocus" size="50">
     <input type="submit" value="Send"><br>
     <textarea disabled="disabled"><?php echo "Sent: $sentChar\nResult: $charResult\n"?></textarea>
     <textarea disabled="disabled"><?php echo "Sent: $sent\n&gt;&gt; $charResults\n"?></textarea>
    </form></body></html>

  8. #8
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,785
    @darkspark, one hopes that you have seen that your original question was answered in this loop, the $STACK array notwithstanding:
    PHP Code:
     function  alphaToPhonetic($post) {  global $STACK;  foreach ($STACK as $alpha => $phonetic) { if ($post == $alpha) return $phonetic; }; }; 
    Every one of the stack of if()'s you asked in the OP is answered here, in this loop. The part that may be difficult to grasp is that we are cycling through an associative array, not an indexed one and we are not working from the post response array, but a sample of the one variable in it that we care to take note of ($_POST['text']).

    We have constructed our array as one of KEY associated with VALUE, and use FOREACH() to break out the cells. This is an IMPLICIT loop which does not need an upper bound pre-declared. When it runs out of keys, it terminates itself. The method is a little bit abstracted from the normal FOR loop, and requires us to place our mind at the abstract level. Get used to doing this and you'll never have trouble with associative arrays, or the loops we use to cycle through them.

    In our example, we only loop through the array as far as we must, and our software has already pre-qualified the input as an uppercase letter so we know there WILL BE a return. The letter 'z' will require 26 loops but 'f' only 6 whereupon the phonetic from the array is returned. As loops go, this is known as a logical breaking point. Luckily for us, there is a RETURN, else this 'point' would require an arbitrary BREAK to terminate the loop.

    As mentioned in my earlier theorizing and preamble, the word version would be more complicated. As it turns out, only another FOREACH() loop. Now we get to see the power in our first loop. We call it over and over again in our second. Notice that as mentioned earlier, we have constructed an array of letter cells so that both loops when carried out, yield a conglomerate of single letter results.
    Last edited by weegillis; 04-09-2012 at 08:07 AM. Reason: grammar / and d'uh moments, too

  9. #9
    Member
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    64
    Seriously weegillis, thank you for the time that you've invested in this. Like I said you did lose me, and I'm gathering my thoughts about the text that you have given within explaining the code that you've put forth, but I feel as though you've over estimated my php programming abilities...

    Any advice on which php book/s I should have a good read through for learning and developing any future skills I hope to possess in PHP?

    Thank you again.
    http://www.dynamicexposure.com - Photography Tutorials, Help and Forum.
    http://tibia.dynamicexposure.com - Tibia game information.
    http://phonetic-code.dynamicexposure.com - Phonetify - Phonetic Code for the words you enter

  10. #10
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,785

    Post

    It can get that way, lots, where I'm thinking a method is straight forward and transparent and the next person is scratching their head as if trying to look through a mirror, nothing transparent about it. My apologies if this is throwing you for a loop (pun intended).

    I just now realized that you have a page up already. Is the code in your OP the same as what's behind that page? I would be interested to see what you have at present. As you can see, our version above has a lot more horsepower than what I imagine is running on your page. If you happen to use this, please leave in the attribution so it doesn't look like you wrote it yourself.

    The OP approach of traversing a tree of if/then may work, but it is incredibly CPU intensive, since it contains so many iterations of 'echo', which is a resource hog. It is also not very compact owing that all the string constants are embedded in the code. You can see for yourself how compact our version above is, and there are virtually no limits on the input phrase, though one might want to impose one within reason.

    Two of many ways to skin a cat. Both work, but we can see how different they are in their approaches. Everybody will take a different angle of approach, depending upon, a) their skill set, b) how well they understand the problem needing to be solved, and c) their ability to visualize and reason before pen hits paper. There is very little that is rote about any programming or scripting language. We need all three above to a certain degree in solving even the simplest problem.

    I learned, and am still learning basic PHP one problem at a time. My biggest resource has always been the PHP manual on their site. W3 Schools also has a lookup guide for basic syntax and usage. You could turn to SitePoint, who have through the years published a handful of PHP related books:

    PHP related products.

    There are others that have been mentioned in threads in the past. @kgun has mentioned some, so if you don't mind a little digging, you may track down some of his posts relating to PHP. As books go, they can only tell you so much. It's all rote until we start getting our hands dirty. That's when the practical learning starts to set in.

    The toughest part I find for most people is the 'sticking to it' part. They find a solution, see that it works, and accept it as is and move on. This is not how we learn programming, even if it does work. Every solution can be made more compact, more efficient, more elegant, more powerful, more... IF we stay with it and come round and round again, each time approaching from a slightly different angle. Eventually, in time, we build up our own understanding and resource kit of ideas and methodologies.

    Even to an experienced programmer (that's not me by the way, I'm a hobbyist) the solution seldom just falls out onto the page. We think about the problem, propose a solution, write something and try it, tweak it, try another method, think on it some more, each time gaining more intimacy with the problem, and each step along the way refining our solution until we hammer it into a solid piece of software. Our example above is about as solid as one can get it, but I bet there are even still some improvements that can be made.

    As you will have noted, in the early discussion on this thread all we did was look at the problem, and visualize the steps that would be involved to arrive at our desired solution. The method falls out from there, and depending on how well the problem has been thought through, our first attempt might work just fine. Going for a finished product off the bat is just not practical. We first need something that works, then we need to make it smarter by setting up error traps that prevent errant data from slipping in, or being returned in our results. The finished product seldom looks like what we first come up with, and nothing gets improved if we don't always challenge ourselves to seek ways to improve it.
    Last edited by weegillis; 04-10-2012 at 12:19 AM. Reason: typo / grammar

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •