Search code examples
phplistglob

PHP random glob sort


I have this simple line:

       $images = glob($directory . "*.html");

It returns a list of files like this:
e.g 1

17001400300120110004600.html
17001400300120110004700.html
17001400300120110004800.html
17001400300120110004900.html
17001400300120110005000.html

The problem is that I don't need an ordered list. I need a random list, like this:

e.g 2

17001400300120110004700.html
17001400300120110005000.html
17001400300120110004900.html
17001400300120110004600.html
17001400300120110005800.html

I've tried with NOSORT ( $images = glob($directory . "*.html", GLOB_NOSORT); ) flag but returns an ordered list like in the first example.

How can I get a random list?


Solution

  • Use shuffle on array returned from glob.

    Using nosort won't make your array random, it will just read them in order they appear in the directory instead of sorting them by name, as documentation states:

    GLOB_NOSORT - Return files as they appear in the directory (no sorting)

    Have in mind that shuffle takes array as referrence so you will need to do just this:

    $images = glob($directory . "*.html");
    shuffle($images);