0

I have a directory with a hundred HTML files that are ordered alphabetically. They are posts to a blog, and I successfully managed to include() them like this:

foreach (glob("posts-en/*.html") as $filename)
{include $filename; }

They all display on my website, but I'd like to reverse the order. I search Stack Overflow, and found an apparent solution with "array_reverse". However if I do this:

foreach (array_reverse(glob("posts-en/*.html") as $filename))
{include $filename;}

It doesn't work. Can anyone help?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ben Viatte
  • 485
  • 1
  • 5
  • 16
  • For what it's worth, nowhere in the [glob()](https://php.net/glob) manual page it's stated that files are ordered by date. Actually, it says explicitly that they're sorted alphabetically by default. – Álvaro González Jul 26 '22 at 08:42
  • Sorry, I should have specified that. In my case, the date is in the filename, hence, "alphabetically" and "by date" are the same here. So in other words, I would like reverse-alphabetical order. I just edited the question – Ben Viatte Jul 26 '22 at 08:47
  • 1
    Your brackets are misplaced. I'm surprised this code actually runs :-? – Álvaro González Jul 26 '22 at 08:56
  • I can't seem to find where I put wrong brackets – Ben Viatte Jul 26 '22 at 09:05
  • 1
    Is that your real code? It triggers a parse error for me: https://3v4l.org/hQfFd#v8.1.8 - You need to apply `array_reverse()` to an array, but you currently apply it to the inner expression of the `foreach()` loop. – Álvaro González Jul 26 '22 at 09:07
  • That is my real code and I'm getting the same error. I asked this question because I couldn't figure out how to syntax it properly. I don't know if I'm taking the right approach – Ben Viatte Jul 26 '22 at 09:10
  • 1
    The `$foo as $bar` syntax only makes sense in a foreach loop. You cannot do `array_reverse($foo as $bar)` any more than you can do `echo $a as $b`. You want `array_reverse($foo) as $bar`, not `array_reverse($foo as $bar)`. – Álvaro González Jul 26 '22 at 09:14
  • Thank you Alvaro, that was my mistake! It solved the problem and my website now works as intended. I wish I could choose yours as the answer but the thread has been closed. – Ben Viatte Jul 26 '22 at 09:19
  • 1
    Don't worry. Such answer wouldn't help anyone else. The parse error is not even mentioned in the question. – Álvaro González Jul 26 '22 at 09:24

0 Answers0