Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

PHP program to add item at the beginning of associative array

  • Last Updated : 11 Feb, 2019

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
  
// Existing array
$arr = array('one' => 1, 'two' => 2);
      
// New element
$arr['zero'] = 0;
      
// Final array
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
      
// Adding a new element at the beginning of an array
  
// Existing array
$arr = array('one' => 1, 'two' => 2, 'three' => 3);
          
// New element to be added at 'zero' => 0
  
// Create an array using the new element
$temp = array('zero' => 0);
      
// Append the $temp in the beginning of $arr
      
// Using array union(+) operator
$arr2 = $temp + $arr;
      
echo "Result of array union(+) : ";
print_r($arr2);
      
// Using array_merge() function
$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
)



My Personal Notes arrow_drop_up
Recommended Articles
Page :