Building an anagram.
Posted: Thu Nov 24, 2011 3:25 pm
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:
But when I run the code, it outputs something similar to this:
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.
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.";
}
?>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