Php
// Existing array
$arr
=
array
(
’one’
= > 1,
’two’
= > 2);
// New element
$arr
[
’zero’
] = 0;
// Final array
print_r (
$arr
);
?>
Exit:Array ([ one] = > 1 [two] = > 2 [zero] = > 0)Thus, a new element cannot be added directly at the beginning of an associative array, but an existing array can be added to the end of the new array, where the first element is the new element.
This means adding a new element at the beginning, first the new element must be placed in an empty array as the first element, and then the array must be concatenated with the existing array. PHP has two ways to merge arrays: the array_merge() function and using the array merge operator (+).In the case of the array_merge() function, if two arrays have the same key, then the value corresponding to the key in the subsequent array is counted in the resulting array. But in the case of an indexed array, the elements are simply added and re-indexing is done for all elements in the resulting array.Syntax:
array array_merge ($arr1, $arr2)In the case of the array concatenation operator (+), if two arrays have the same key, then the value corresponding to the key in the first array is considered in the resulting array, this also applies to an indexed array, if two arrays have a common index element, then only the element from the first array will be taken into account in the resulting array.Syntax:
$arr3 = $arr1 + $arr2Program:PHP program to add a new element at the beginning of an associative array.
php
// Add a new element at the beginning of the array
// Existing array
$arr
=
array
(
’one’
= > 1,
’two’
= > 2,
’three’
= > 3);
// New element to be added to ’ zero ’ = > 0
// Create an array using the new element
$temp
=
array
(
’zero’
= > 0);
// Add $temp at the beginning of $arr
// Using the array concatenation operator (+)
$arr2
=
$temp
+
$arr
;
echo
" Result of array union (+): "
;
print_r (
$arr2
);
// Using the array_merge() function
$arr3
=
array_merge
(
$temp
,
$arr
);
echo
" "
.
"Result of array_merge():"
;
print_r (
$arr3
);
?>
Exit: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)