Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to insert an element into the middle of an array

Short answer

array_splice() with length 0 removes nothing and inserts the element at the given place:

<?php
 
$steps = ['cart', 'payment', 'done'];
 
array_splice($steps, 1, 0, 'address');
 
echo implode(' > ', $steps);

Output:

cart > address > payment > done

Several elements

Pass an array:

<?php
 
$numbers = [1, 2, 5];
 
array_splice($numbers, 2, 0, [3, 4]);
 
echo implode(', ', $numbers);

Output:

1, 2, 3, 4, 5

At the start

array_unshift() does that:

<?php
 
$queue = ['second', 'third'];
array_unshift($queue, 'first');
 
echo implode(', ', $queue);

Output:

first, second, third

Functions used in this recipe

  • array_splice — Removes part of an array and optionally inserts new elements in its place.
  • array_unshift — Prepends elements to the beginning of an array.
  • array_merge — Merges one or more arrays into one.

Thanks for reading!

Donate to the site — we work hard for you.