How to add/Insert an Element in a Specific Position in an Array using PHP?


You have an array which has some elements (see the following array). You want to insert an element (ex. Wednesday) in the fourth position in the array.

$days = array("Sunday", "Monday", "Tuesday", "Thursday", "Friday", "Saturday");


We can accomplish this in three steps-

Step 1: Slice the array in the position where we want to insert new element and make it two arrays.
Step 2: Create a new array and insert the new element (Wednesday) that we want to add in the desired key number.
Step 3: Merge all three arrays into one.

See the following example –

$days = array("Sunday", "Monday", "Tuesday", "Thursday", "Friday", "Saturday");

$first_half_arr = array_slice($days, 0, 3, true);
$second_half_arr = array_slice($days, 3, 3, true);
$new_element_arr = array(3=> "Wednesday");
$revised_arr = array_merge($first_half_arr, $new_element_arr, $second_half_arr);

[wpdm_file id=87]


    [0] => Sunday
    [1] => Monday
    [2] => Tuesday
    [3] => Wednesday
    [4] => Thursday
    [5] => Friday
    [6] => Saturday

How it works:

Line 3 The $day[] is the array we’ll work on. We’ll insert Wednesday after Tuesday. We’ll divide the array into two. One array will hold elements from the beginning upto Tuesday and the other array will hold the rest.
Line 5 The array_slice() function will extract first three elements from the $days[] array and will create a new array $first_half_arr[] with those elements. Here, the first parameter $days is our primary array. The second parameter 0 indicates that the extraction will be begun from 0 index position. The third parameter 3 ensures that the three elements will be exctracted. By default, after ectraction array_slice() function reindex the numeric array indices. To preserve the original keys in the new array, we used TRUE in the fourth parameter.
Line 6 The array_slice() function will extract 3 elements(third parameter) starting from the fourth position(second parameter) which is indicated by 3 and will create a new array $second_half_arr with those elements.
Line 7 Here, we make a new array $new_element_arr which has only one element Wednesday in its fourth position. Note: array array keys starts with index 0.
Line 8 array_merge() function will merge all three functions into one.
Line 9 Here, we print the final array.