In PHP associative array is the type of array where the index need not to be strictly sequential like indexed array. Normally add a new element in an existing associative array it will get appended at the end of that array.
Array ( [one] => 1 [two] => 2 [zero] => 0 )
So, a new element can not be added directly at the beginning of an associative array but the existing array can be appended at the end of a new array where the first element is the new element.
It means add the new element in the beginning first the new element need to be put in an empty array as first element and then the array need to be merged with the existing array. In PHP, there are two ways to merge arrays they are array_merge() function and by using array union(+) operator.
In case of array_merge() function if two arrays have a same key then the value corresponding to the key in later array in considered in the resulting array. But in case of indexed array the elements simply get appended and re-indexing is done for all the element in the resulting array.
array array_merge( $arr1, $arr2 )
In case of array union(+) operator if two arrays have same key then the value corresponding to the key in first array in considered in the resulting array, this also applies in the indexed array, if two array have an element of common index then only the element from first array will be considered in the resulting array.
$arr3 = $arr1 + $arr2
Program: PHP program to add a new item at the beginning of an associative array.
Result of array union(+) : Array ( [zero] => 0 [one] => 1 [two] => 2 [three] => 3 ) Result of array_merge() : Array ( [zero] => 0 [one] => 1 [two] => 2 [three] => 3 )
- How to insert an item at the beginning of an array in PHP ?
- Program to Insert new item in array on any position in PHP
- How to loop through an associative array and get the key in PHP?
- Multidimensional Associative Array in PHP
- How to remove a key and its value from an associative array in PHP ?
- How to get numeric index of associative array in PHP?
- Convert an object to associative array in PHP
- How to check an array is associative or sequential in PHP?
- Iterate associative array using foreach loop in PHP
- How to access an associative array by integer index in PHP?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.