2

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!

4
  • 3
    $reverse_months = array_reverse($months,true); Commented Dec 19, 2016 at 14:56
  • did you try $reverse_months = array_reverse($months, true);? Commented Dec 19, 2016 at 14:56
  • Try this array_reverse($input, true) ; Commented Dec 19, 2016 at 14:56
  • php.net/manual/en/function.array-reverse.php to see a description of array_reverse Commented Dec 19, 2016 at 14:57

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, sometimes the answer is so simple that it makes you mad :D Life saver, thank you very much!

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.