1

Is there a way to loop through a foreach loop opposite to the way it normally goes? For example, I have an unknown amount of files in the $_FILES variable ($_FILES['file'], $_FILES['file2'], $_FILES['3'] etc...). Using this code

foreach($_FILES as $i)

$i will output as file3, file2, file. I need it to output file, file2, file3.

3 Answers 3

6

array_reverse should do the trick:

foreach(array_reverse($_FILES) as $i)
Sign up to request clarification or add additional context in comments.

Comments

4
foreach(array_reverse($_FILES) as $i)

Comments

3

Here's another way without using a for:

$i = count($_FILES);
while ($i-->0)
    // Do stuff

I think it's ever so slightly prettier.

Some years later, I look back at this and I frown.

6 Comments

Maybe if you added some spaces and did pre-decrement :)
No no no, I like it better this way. It works, and it looks like an arrow. That alone makes it better. It's sort of the hipster loop. It's a bit obscure; you probably haven't heard of it. It's much more poetic than those other mainstream for loops.
You're totally right. I haven't heard of writing obscure code that is difficult to read for future developers. Very hip man!
This will only work if the array is numerically indexed, which it doesn't appear to be in the question. It is also hard to understand and therefore not easily maintainable, which in itself deserves a downvote.
I used a modified version of this.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.