PHP Array_unshift () Function

PHP

Syntax :
int array_unshift ($array, $val1, $val2, $val3 ....)
Parameters:
The function can take several parameters depending on the number of elements that we want to insert into the array. We have basically classified the parameters into two categories, as described below:
  • $array:this is a required parameter and refers to the original array we want to work with.
  • List_of_values ​​: This is a group of parameters representing a list of values ​​that we need to insert into the array, $array. In the above syntax, List_of_values ​​is $val1, $val2, $val3….,
  • Return value:this function returns the total elements in the new modified array after inserting the elements.Examples:
    Input: $array = ("ram", "krishna", "aakash") $val1 = "rohan", $val2 = "rajeeb", $val3 = "saniya" Output: Array ([0] = > rohan [1] = > rajeeb [2] = > saniya [3] = > ram [4] = > krishna [5] = > aakash) Input: $array = (1 = > "ram", 2 = > "krishna", 3 = > "aakash") $val1 = "rohan", $val2 = "rajeeb", $val3 = "saniya"; Output: Array ([0] = > rohan [1] = > rajeeb [2] = > saniya [3] = > ram [4] = > krishna [5] = > aakash)  The following programs illustrate the array_unshift() function in PHP:
    • In this program, we will try to understand how array_unshift() works by adding elements to the beginning of the array. We will also notice that the number keys are added automatically. < tbody>  
      // PHP illustration program
      // using array_unshift() 
      // Input Array $array = array ( "ram" , "krishna" , "aakash" );  
      // Values ​​to be added $a1 = "rohan" ; $a2 = "rajeeb" ; $a3 = "saniya" ;  
      // Callig array_unshift() array_unshift ( $array , $a1 , $a2 , $a3 );  
      // Print the modified array print_r ( $array );  
      ?>
      Output:
      Array ([ 0] = > rohan [1] = > rajeeb [2] = > saniya [3] = > ram [4] = > krishna [5] = > aakash)
    • In the above program, we saw that if a non-key array is passed to the array_unshift() function, then it is automatically converted to an array with numeric keys. But if the array already had numeric keys starting from zero, then after inserting new elements, the keys will be changed. The program below illustrates this:   // PHP illustration program
      // using array_unshift() 
      // Input Array $array = array (1 = > " ram " , 2 = > " krishna " , 3 = > "aakash" );  
      // Values ​​to insert $a1 = "rohan" ; $a2 = "rajeeb" ; $a3 = "saniya" ;  
      // Call array_unshift() array_unshift ( $array , $a1 , $a2 , $a3 );  
      // Print the modified array print_r ( $array );  
      ?>
      Output:
      Array ([ 0] = > rohan [1] = > rajeeb [2] = > saniya [3] = > ram [4] = > krishna [5] = > aakash)
    Link :
    http: // php. net / manual / en / function.array-unshift.php