Home >Backend Development >PHP Tutorial >How Can I Insert an Item at a Specific Position in a PHP Array?
Inserting an Item at an Arbitrary Position in a PHP Array
Want to add an item to your PHP array at a specific position without overwriting existing elements? Let's explore a hassle-free way to do it using array_splice.
Using array_splice
The array_splice function is a powerful tool for manipulating arrays. It can insert, remove, or replace elements within an array. To insert a new item, you'll need to specify the following parameters:
Example:
Let's say you have an array called $original containing the elements 'a', 'b', 'c', 'd', 'e', and you want to insert 'x' after 'c'. Here's the code:
$original = array( 'a', 'b', 'c', 'd', 'e' ); $inserted = array( 'x' ); array_splice( $original, 3, 0, $inserted ); // $original is now a b c x d e
Note:
The above is the detailed content of How Can I Insert an Item at a Specific Position in a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!