There is absolutely nothing wrong with using a lengthy code, if it works.
Once you have a working, although, lengthy code, there are several helpers on this forum, which will be more than happy to review your code, and make suggestions as to how you can make it shorter and/or faster (note: one does not necessarily mean the other)

Regarding checking if the numbers are in the correct location or not, using a loop and comparing to instances of $mid is a good way of doing this.

You might want to take a look at my Scrambled Word Game snippet, as it appears to be similar to what you're trying to do.