PHP

Tutorials and guides on PHP

Adding arrays together while preserving keys in PHP

Written by: Peter Fisher on February 18, 2013
Tagged under:
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

PHP Hypertext Preprocessor
In this post I will demonstrate how to add arrays together without losing or reassigning the array keys in PHP. This is handy if you want to combine two arrays which have defined keys.  For example lets say you have the following arrays:

If you use the php function array_merge the array keys will be renumbered like so:

As you can see the keys are be reindexed and start from 0. The solution is not to use any of the PHP inbuilt functions but  simply use the plus symbol (+) to add both arrays together.

This gives us the desired output of:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Peter Fisher is a web developer working in Gloucester UK. Founder of the digital agency Websomatic, author of this blog and the HowToCodeWell Youtube channel. Peter has over ten years of web development experience under his belt

Read all about Peter Fisher

Leave a Reply

Your email address will not be published. Required fields are marked *