Sometimes, we want to insert a new item in an array on any position in PHP.
In this article, we’ll look at how to insert a new item in an array on any position in PHP.
How to insert a new item in an array on any position in PHP?
To insert a new item in an array on any position in PHP, we can use the array_splice
function.
For instance, we write
$original = ["a", "b", "c", "d", "e"];
$inserted = ["x"];
array_splice($original, 3, 0, $inserted);
to call array_splice
with $original
, 3, 0, anmd $inserted
to insert the entries at $inserted
into position 3 and beyond while removing 0 existing entries from the $original
array.
Conclusion
To insert a new item in an array on any position in PHP, we can use the array_splice
function.