Search code examples
phpmysqlanagram

anagram finder program php mysql


i am trying to write a program for anagram finder in php mysql.. i have dictionary in database which has only one field named 'word' and it contains 500000 rows.

by using php i tried to pull words one by one from database.. After getting a word i created 2 for loops which performs character by character comparison..

for example.. let the input word be 'abcdef'..

consider i am fetching the word 'fade' from database..

i am writing a loop and checking whether the word fade is in abcdef .. if yes i am printing the word.. if not, i will fetch next word from database..

i wrote the code.. but i am getting an empty page as output.. pls help..

i have one more question. is there any other way to find the substring of a word without using character by character comparison?

for example : if my input is fedcba.. i sort it as abcdef.. and dictionary word is fade and i sort it as adef.. is thr any function to find whether adef is a substring of abcdef..


Solution

  • Forget checking each word in PHP. That's a CPU nightmare!

    Add a second column to your table, and have the word spelled out in alphabetical order. For example:

    Word : AlphaWord
    Test : estt
    

    Then you can simple run a query like this:

    select word from table 1 where AlphaWord = (select AlphaWord from table1 where word='$yourWord') order by word asc;
    

    Edit: If you didn't want to match words within other words, you could pop a Fulltext search index on the AlphaWord column and then use the Match()... against() syntax which will return the matches very fast. However, as this operator would only allow for a wildcard to be placed on the end of a search string, it won't match machete->aceehmt with ache->aceh. Having said that, to be honest, you couldn't really add in a wildcard in a normal search either that would match them.