Incidentally, it's an awfully complicated way of getting a list of files that end in ".jpg" - complicated and wrong (It would match a file named "ajpgio.png", for example).
A simpler way of getting a list of files with a ".jpg" extension would be to use [man]glob[/man].
If necessary (i.e., if, you can't guarantee that the above is sufficient), might be an idea to get a list of files with an extension of ".jpeg" as well, and merge them together. And - again if necessary - each could then be checked to see if it really is a JPEG image with [man]getimagesize[/man].