I am completely new to PHP. Today I just have a problem that I can’t figure out how to solve it, even after google searching and digging SOF. This is the Anagram algorithm.
So, I understand the problem here: when the user enters a string, I split it and compare it with my library (this array), then I will have to attach it to the 2-3 characters ... etc. compare again, exactly where I am stuck now, I do not know how to join the elements of the array.
Here is the code that I am implementing, as well as a sample dictionary.
I have a makeshift dictionary with these elements in the $ dict array. And I have a form for a user to enter a string, the entered string will be passed to the code below and declared as $ anagram. I need to split the string entered for comparison with my dictionary. But I don’t know how to join them by comparing 2 letters, 3 letters ... etc. Etc., in the dictionary.
<?php
$dict = array(
'abde',
'des',
'klajsd',
'ksj',
'hat',
'good',
'book',
'puzzle',
'local',
'php',
'e');
$anagram = $_POST['anagram'];
//change to lowercase
$anagram = strtolower($anagram);
//split the string
$test = str_split($anagram);
//compare with $dict for the first split without joining
for ($i=0; $i<strlen($anagram); $i++) {
if ($test[$i]==$dict[$i]) {
echo $test[$i]."<br />";
}
}
//problem: how to join elements of the array in the loops
//like user inputs "hellodes"
//after echo "e", how to join the elements like: h-e,h-l,h-l,h-o,h-d,h-e,h-s
//and then h-e-l,h-e-l,h-e-o...etc...
?>
I hope to get the algorithm as simple as possible because I'm completely new. And I'm sorry because my English is not so good. Best regards, Hiem Nguyen.