PHP program to add item at the beginning of associative array
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.
Example:
<?php
$arr = array ( 'one' => 1, 'two' => 2);
$arr [ 'zero' ] = 0;
print_r( $arr );
?>
|
Output:
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.
Syntax:
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.
Syntax:
$arr3 = $arr1 + $arr2
Program: PHP program to add a new item at the beginning of an associative array.
<?php
$arr = array ( 'one' => 1, 'two' => 2, 'three' => 3);
$temp = array ( 'zero' => 0);
$arr2 = $temp + $arr ;
echo "Result of array union(+) : " ;
print_r( $arr2 );
$arr3 = array_merge ( $temp , $arr );
echo "\n" . "Result of array_merge() : " ;
print_r( $arr3 );
?>
|
Output:
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
)
Last Updated :
11 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...