We can add an element in the beginning of an array using array_unshift method. Its quite easy and handy, But did you know that array_unshift will reindex you array? Thats what I like to discuss over this blog post.
Lets take the above php array as sample. I intentionally missed the indexes 3 and 4 to show array_unshift method will reindex your array.
See the Fifth is moved to 3rd index? This will happen only when the indexes are numeric.
So the easy way to append an element in the beginning of an array without reindexing is using “+” operator on array.
Now the “Fifth” element is still on index 5.
Hope you will be careful when using array_unshift next time.