PHP : Add element in the beginning of an array

August 6th, 2013 § 0 comments

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.

Revath S Kumar [RSK]

- Rubyist / JavaScripter - Yeoman Team member - Open source enthusiast - Blogger @ PHPRepo and - Coder @ Whatznear - Google fanboy - jQuery lover

More Posts - Website - Twitter - Facebook - LinkedIn - Pinterest - Google Plus - YouTube


Comments are closed.