Sling Academy
Home/PHP/How to Insert an Element into an Array in PHP

How to Insert an Element into an Array in PHP

Last updated: January 10, 2024

Overview

Working with arrays is a fundamental skill in programming, and PHP offers a rich set of functionalities to manipulate them. Inserting an element into a PHP array can seem straightforward, but there are a variety of ways to do it, each suited to different circumstances. This tutorial will guide you through the techniques of inserting elements, whether it is at the beginning, middle, or end of an array, and discuss the trade-offs for each method.

Basic Insertion Techniques

Adding to the End of an Array

One of the simplest operations is adding an element to the end of an array. The array_push() function adds one or more elements to the end of an array:

$array = ['apple', 'banana', 'cherry'];
array_push($array, 'date');
print_r($array);
// Output: Array
// (
//     [0] => apple
//     [1] => banana
//     [2] => cherry
//     [3] => date
// )

The $_POST array will now include a new item, ‘date’, at the end.

Inserting at the Beginning

To insert an element at the beginning of an array, you can use the array_unshift() function:

$array = ['apple', 'banana', 'cherry'];
array_unshift($array, 'apricot');
print_r($array);
// Output: Array
// (
//     [0] => apricot
//     [1] => apple
//     [2] => banana
//     [3] => cherry
// )

The ‘apricot’ element is now the first item in the array.

Inserting at a Specific Position

For inserting an element at any given position, use array_splice(). This function is more flexible and can remove as well as insert elements.

$array = ['apple', 'banana', 'cherry'];
array_splice($array, 1, 0, 'blueberry');
print_r($array);
// Output: Array
// (
//     [0] => apple
//     [1] => blueberry
//     [2] => banana
//     [3] => cherry
// )

This code added ‘blueberry’ to position 1, without removing any items (0 is the length parameter which tells how many items to remove).

Advanced Insertion Techniques

Insert Multiple Elements at a Specific Position

To insert multiple elements, use array_splice() similarly as before, but pass the elements as an array:

$array = ['apple', 'cherry'];
array_splice($array, 1, 0, ['banana', 'blueberry']);
print_r($array);
// Output: Array
// (
//     [0] => apple
//     [1] => banana
//     [2] => blueberry
//     [3] => cherry
// )

This operation inserted ‘banana’ and ‘blueberry’ starting at position 1.

Insert with Array Combination

Sometimes it might be necessary to combine arrays. You can add one array into another using the array_merge() function:

$array1 = ['apple', 'banana'];
$array2 = ['cherry', 'date'];
$combined = array_merge($array1, $array2);
print_r($combined);
// Output: Array
// (
//     [0] => apple
//     [1] => banana
//     [2] => cherry
//     [3] => date
// )

In this case, array_merge() has combined $array1 and $array2 into one new array.

Handling Associative Arrays

Associative arrays use keys instead of numerical indexes. Insertion in associative arrays needs preserving the keys.

Inserting an element into an associative array can be done by directly setting the element using its key:

$assocArray = ['a' => 'apple', 'b' => 'banana'];
$assocArray['c'] = 'cherry';
print_r($assocArray);
// Output: Array
// (
//     [a] => apple
//     [b] => banana
//     [c] => cherry
// )

For a position-based insertion, you’d need to manually split and combine arrays:

$assocArray = ['a' => 'apple', 'c' => 'cherry'];
$start = array_slice($assocArray, 0, 1, true);
$end = array_slice($assocArray, 1, null, true);
$insert = ['b' => 'banana'];
$assocArray = array_merge($start, $insert, $end);
print_r($assocArray);
// Output: Array
// (
//     [a] => apple
//     [b] => banana
//     [c] => cherry
// )

Performance Considerations

Choosing the right method for inserting elements is also about understanding performance impacts. For example, array_unshift() is slower on large arrays because it has to reindex the array. On the contrary, array_push() and direct assignment ($array[] =) perform better as they avoid reindexing.

Conclusion

Inserting elements in PHP arrays can be done in numerous ways. Using array_push(), array_unshift(), and array_splice() provides flexibility for handling indexed arrays, while associative array insertion often involves direct key assignment or array merging. Whichever method you choose, be mindful of the array’s structure and performance considerations, especially with larger data sets.

Next Article: How to Prepend an Element to an Array in PHP

Previous Article: How to Append Elements to an Array in PHP

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array