How to add a value to an array on a specific index

Summary:

There are many built-in PHP functions you can use to set a value on a specific index on an array. We recommend creating a custom function but you can use array_splice, array_slice, array_push, or array_unshift to accomplish this reqest.

Add a value to an array on a specific index

There are two popular options to add a value to an array at a specific index. This article reviews both these options and includes notes about appending or prepending to an array.

Introduction

Array values have specific indexes starting from zero. Sometimes, we may want to add at a random index other than the two extreme ends. This operation is often necessary if the order of the values is essential. So, this article explores a couple of options to add a value to an array PHP. So, let’s jump straight to the main article without any further ado.

add a value to an array

#1 – Add a value to an array using array_splice

PHP array_splice adds a replacement value or array at a specific index whilst removing a portion from the index to a specified length. The array_splice function has several arguments, and understanding these can help in using it the right way.

array_splice( array &$array, int $offset, ?int $length = null, mixed $replacement = [] ) : array

The arguments offset and length are the two crucial arguments. This article is not meant to explain these details. If you want to learn more about this function, check out an in depth article about this function. So, let’s jump straight to the example of how to add a value to an array PHP at a specific index.

Example – Add a value to an array

The first example includes an array of names. We’ll add another name to the third index.

<?php
$names = ['Micheal','Andrei','Ron', 'Arthur'];
 
array_splice($names, 3, 0, 'Brian');
 
print_r($names);
 
/*
Array
(
    [0] => Micheal
    [1] => Andrei
    [2] => Ron
    [3] => Brian
    [4] => Arthur
)
*/
?>

So, the example adds ‘Brian’ to the array of names at an index of three. Notice that the offset gets the index, and the length argument is zero. The zero length argument ensures nothing is removed from the names.

#2 – Add a value to an array using array_slice

PHP array_slice returns a portion of the array based on its two crucial arguments: offset and length.

array_slice( array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array

The function can be confusing for starters. So, we have done an article on this function that includes some visuals for better understanding this function for different combinations of offset and length arguments.

Moreover, we’ll also be using array_merge to accumulate the sliced array back. We have you covered on array_merge function too. Just make sure to get familiar with it. So, let’s cut all this crap and move to the example.

Example

This example adds the name ‘Susi’ to the second index.

<?php
$names = ['Micheal','Andrei','Ron','Brian', 'Arthur'];
 
$names = array_merge(array_slice($names, 0, 2), ['Susi'], array_slice($names,2));
 
print_r($names);
 
/*
Array
(
    [0] => Micheal
    [1] => Andrei
    [2] => Susi
    [3] => Ron
    [4] => Brian
    [5] => Arthur
)
*/
?>

So, there are two calls to array_slice within the array_merge. Let’s see what each call returns.

  • array_slice($names, 0, 2)  –  [ ‘Micheal’, ‘Andrei’]
  • array_slice($name, 2)        –  [ ‘Ron’, ‘Brian’, ‘Arthur’]

Also, see that the name ‘Susi’ is passed in an array. That’s because the array_merge accepts arrays only. Finally, the array_merge combines the arrays. 

#3 – Add a value to an array using array_push

PHP array_push is a standard function for adding values at the end of an array. So, if the specific index happens to be the end of an array then its an array_push call.

Example

<?php
$names = ['Micheal','Andrei','Susi','Ron','Brian', 'Arthur'];
 
array_push($names, 'Bob');
 
print_r($names);
 
/*
Array
(
    [0] => Micheal
    [1] => Andrei
    [2] => Susi
    [3] => Ron
    [4] => Brian
    [5] => Arthur
    [6] => Bob
)
*/
?>

#4 – Add a value to an array using array_unshift

PHP array_unshift is ideal if add new value to array start. Here’s an example.

<?php
$names = ['Micheal','Andrei','Susi','Ron','Brian', 'Arthur', 'Bob'];
 
array_unshift($names, 'Shaun');
 
print_r($names);
 
/*
Array
(
    [0] => Micheal
    [1] => Andrei
    [2] => Susi
    [3] => Ron
    [4] => Brian
    [5] => Arthur
    [6] => Bob
    [7] => Shaun
)
*/
?>

#5 – Add a new value to array with a customized function

Here’s a custom function that handles the situation well. However, a limitation here is that it only works for positive index values. Of course, negative indexes are crucial too, but we’ll leave that for you. Check out if you can add more logic to it.

function addAtIndex($arr, $index, $element)
{
    if(count($arr) < $index)
    {
        throw new Exception("Index out of bound");
    }
 
    if($index < 0)
    {
        throw new Exception("Negative index not supported");
    }
 
    $curr = $arr[$index];
    $arr[$index] = $element;
 
   
    for($i = $index + 1; $i < count($arr); $i++)
    {  
            $temp = $arr[$i];
            $arr[$i] = $curr;
            $curr = $temp;
    }
 
    $arr[count($arr)] = $curr;
 
    return $arr;
}

Example – Adding at a random index

Here’s an example of the customized function addAtIndex with a random index, say fourth.

<?
$names = ['Micheal','Andrei','Susi','Ron','Brian', 'Arthur', 'Bob'];

$names = addAtIndex($names, 4, 'Travis');
 
print_r($names);
 
/*
Array
(
    [0] => Micheal
    [1] => Andrei
    [2] => Susi
    [3] => Ron
    [4] => Travis
    [5] => Brian
    [6] => Arthur
    [7] => Bob
)
*/
?>

Personal opinion

I prefer array_splash for adding value to an array at an index other than the extreme ends. This function makes in place changes and that too in one call. Contrary to this, the array_slice option requires a couple of function calls. Moreover, I prefer array_push to append to an array and array_unshift to add a value to an array start.

Conclusion

So, this article covers a lot of ground trying to explore multiple options of adding values to an array to a specific index at PHP. The first option is using the array_splice followed by the array_slice option. The other sections show array_push and array_unshift for appending and prepending values to an array.

Finally, the article includes a customized function that handles positive indexes. Hopefully, you have learned something new today about PHP. Keep learning with us through intuitive and detailed tutorials and articles at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems