osappuk
osappuk

Reputation: 51

Reverse array in PHP with wrong indexes

In PHP, I have an array like this:

Array ( 
    [12] => Dec 
    [01] => Jan 
    [02] => Feb 
    [03] => Mar 
    [04] => Apr 
    [05] => May 
    [06] => Jun 
    [07] => Jul 
    [08] => Aug 
    [09] => Sep 
    [10] => Oct 
    [11] => Nov 
) 

I then do something like this: $reverse_months = array_reverse($months);

What I don't understand is why the result coming out like this:

Array ( 
    [0] => Nov 
    [1] => Oct 
    [09] => Sep 
    [08] => Aug 
    [07] => Jul 
    [06] => Jun 
    [05] => May 
    [04] => Apr 
    [03] => Mar 
    [02] => Feb 
    [01] => Jan 
    [2] => Dec 
)

You can clearly see the last three months of the years got wrong indexes compare to original $months array :-(

Could anyone is kind enough to explain why this weird behavior happens and how can I fix it please? The outcome result is my desirable outcome except the wrong array index for month Oct, Nov and Dec. Thank you!

Upvotes: 2

Views: 314

Answers (1)

B.G.
B.G.

Reputation: 6016

10, 11 and 12 are numeric keys, where 01, 02 and so on are named keys, what php does is reenumerating the numbered keys. There are 3 of them so 0,1,2. Named keys are not reenumerated (How should they ?). To also preserve integer keys, use

array_reverse($months, true);

Upvotes: 5

Related Questions