PHP Merge Array Values With Same Keys
Last Updated : Jul 1, 2023
In this tutorial we will ihow you the solution of PHP merge array values with same keys, this merging is different of simple merging of arrays, if you want to know about simple merging of array then there is already an article provided with the help of which you understand how to merge arrays in simple way.
Here, below we are going to merge array values having same key.
Step By Step Guide On PHP Merge Array Values With Same Keys :-
It means that the values of the keys are different but the keys are same.
And if you use simple array merge function then it will replace the older one and store new value by overriding previous value. Let us understand it with help of codes.
<!DOCTYPE html> <html> <head> <title> Title of the document is here </title> </head> <body> <?php $a1=array("a"=>"1","b"=>"2"); $a2=array("c"=>"3","b"=>"4"); $c = array_merge_recursive($A,$B); echo "<pre>"; print_r($c); echo "</pre>"; ?> </body> </html>
- Here, first of all we already say that to run php we must knew about the basic structure of php. If you don’t about the basic structure of php then you can visit to our articles in which we learn about basic structure of php.
- In next step, we say that we can embed html and php both in each other. There are some rules to integrate them. Please understand before working with php in html.
- Here, in this article first we open and close basic php tags and create head, which is again paired tag. Now, inside head we use title. Title is used to give a title to webpage.
- Now, after end of head and title. We start body, body is the tag in which if we want to show something on webpage then we use this. Body is also a paired tag and have closing tag.
- Now, inside body we open and close php tags. <?php is opening tag for php and ?> is closing tag for php just like html.
- Inside php we create two arrays with some keys and values you can see arrays in above example and then we store it into some variables. In our case, we store in $a1 and $a2.
- Now, here combining and say merging starts. We use here array_merge_recursive function to merge arrays and store them into $c.
- Now, in last step we just print $c with the help of pre tag of html. and store array will be displayed to your screen.
- We hope that you understand the codes properly with the help of steps given above.
At last in conclusion, here we can say that with the help of this article we are able to merge array values with same keys. I hope this tutorial on PHP merge array values with same keys helps you.