![]() |
VOOZH | about |
Arrays in PHP are a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key.
There are some methods to insert an item at the beginning of an array which are discussed below:
Table of Content
The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.
Example:
Array ( [0] => GeeksforGeeks [1] => Computer [2] => Science [3] => Portal [4] => Welcome )
The array_unshift() function is used to add one or more elements at the beginning of the array.
Example 1:
Array ( [0] => Welcome [1] => GeeksforGeeks [2] => Computer [3] => Science [4] => Portal )
Example 2:
Array ( [0] => Welcome [p] => GeeksforGeeks [q] => Computer [r] => Science [s] => Portal )
Using array_splice() to insert an item at the beginning of an array works by specifying the position (0) where the new element should be inserted, setting the length to 0 (no elements removed), and adding the new element, thus modifying the original array in place.
Example:
Array ( [0] => Welcome [p] => GeeksforGeeks [q] => Computer [r] => Science [s] => Portal )
This method manually constructs a new array by specifying the element to be added first, followed by the elements of the original array. This way, the new element is inserted at the beginning of the array.
Example: In this example, the insertAtBeginning function takes an array and an element as parameters. It creates a new array with the specified element at the first position, followed by the elements of the original array using the array_merge function.
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
The array_pad() function can also be used to insert an item at the beginning of an array. This function pads the array to the specified length with a value, either adding to the beginning or end.
Example: In this example we pads the array $array with the value 1 at the beginning, extending its length to ensure it starts with [1, 2, 3, 4].
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
The "+" operator in PHP merges two arrays into a single array, preserving keys from the first array. When inserting an item at the beginning of an array, the "+" operator concatenates the new item with the original array, placing the new item at index zero.
Example
Array ( [0] => apple [1] => cherry )
This method involves reversing the original array, adding the new element at the end using array_push(), and then reversing the array again to restore the original order with the new element at the beginning.
Steps:
Example:
Array ( [0] => Welcome [1] => GeeksforGeeks [2] => Computer [3] => Science [4] => Portal )