Home > Backend Development > PHP Tutorial > How to Insert an Item into a PHP Array at a Specific Index?

How to Insert an Item into a PHP Array at a Specific Index?

Barbara Streisand
Release: 2024-12-14 07:21:27
Original
777 people have browsed it

How to Insert an Item into a PHP Array at a Specific Index?

How to Insert an Item into an Array at a Specific Position in PHP

Inserting a new element into an array at a specific position can be achieved using the array_splice function in PHP. This function allows for both insertion and removal of elements within an array.

To insert an item, provide the following parameters to array_splice:

  • $array: The target array to modify.
  • $start: The position where the insertion should occur; indexes in PHP begin from 0.
  • $length: Set to 0 as we are not removing any elements.
  • $replacements: The item(s) to be inserted.

For instance, the following code inserts the string "x" into the middle of the array $original:

$original = array('a', 'b', 'c', 'd', 'e');
$inserted = array('x');

array_splice($original, 3, 0, $inserted);

// $original is now: array('a', 'b', 'c', 'x', 'd', 'e')
Copy after login

Note: If the replacement is a single element, you can omit the array brackets around it, unless the element itself is an array, object, or NULL.

Caution: The array_splice function modifies the original array in place and does not return the modified array. Therefore, it's important to assign the modified array to a new variable if you wish to preserve the original array.

The above is the detailed content of How to Insert an Item into a PHP Array at a Specific Index?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template