Building an anagram.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikeashfield
Forum Contributor
Posts: 159
Joined: Sat Oct 22, 2011 10:50 am

Building an anagram.

Post by mikeashfield »

I'm trying to generate an anagram based on input from two text fields on form.html but I'm having trouble getting the anagram generator to work.

Here's the code that I have:

Code: Select all

<?php
  if (isset($_POST['firstName']) && isset($_POST['secondName'])) {
      if (strlen($_POST['firstName'])>1 && strlen($_POST['secondName'])) {
          $fName=$_POST['firstName'];
          $sName=$_POST['secondName'];
          $fullName=$fName.$sName;
          $anagram="";         
          echo "Name you provided: ".$fName. " ".$sName."<br>";
          echo "Name backwards: ".strrev($fullName)."<br>";
          echo "Name length: ".strlen($fullName)."<br>";
          for ($counter=0; $counter<=strlen($fullName); $counter++) {
              //Print the loop count.
              echo $counter."<br>";
              //Generate a random number between the number zero (1) and the length of the namestring.
              $charPosition=rand(0,strlen($fullName));
              //Build the anagram.
              $anagram = $anagram & substr($fullName, $charPosition, 0);
              //Print the anagram.
              echo $anagram."<br>";             
          }          
          //echo the anagram
          echo "<br><br><br>".$anagram;          
      }
      else {
          echo "One or more of the names you provided were invalid. Please try again.";
      }
  }
  else {
      echo "You must enter values in both name fields. Please try again.";
  }
?>
But when I run the code, it outputs something similar to this:

Code: Select all

Name you provided: Mike Ashfield
Name backwards: dleifhsAekiM
Name length: 12
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
0
9
0
10
0
11
0
12
0



0
There's no real reason for writing this code other than to learn different string manipulation functions in PHP so the code may be a little buggy.
mikeashfield
Forum Contributor
Posts: 159
Joined: Sat Oct 22, 2011 10:50 am

Re: Building an anagram.

Post by mikeashfield »

Never mind! str_shuffle() does just the trick! :D
Post Reply