Using PHP array_unshift, array_push, and array_splice to Insert Elements
This tutorial demonstrates how PHP's array_unshift, array_push, and array_splice functions can be used to insert single or multiple elements at the beginning, end, or arbitrary positions of an array, with example code and output illustrations.
1. array_unshift() – inserting elements at the beginning of an array
<code>$fruits = array('apple','pear','banana','orange');
array_unshift($fruits, 'cherry');
pr($fruits);
function pr($str){
echo "<pre>";
print_r($str);
echo ""; }
Output:
<code>Array(
[0] => cherry
[1] => apple
[2] => pear
[3] => banana
[4] => orange
)
</code>array_unshift can also accept multiple elements:
<code>$fruits = array('apple','pear','banana','orange');
array_unshift($fruits, 'cherry', 'pie');
pr($fruits);
</code>Output:
<code>Array(
[0] => cherry
[1] => pie
[2] => apple
[3] => pear
[4] => banana
[5] => orange
)
</code>2. array_push() – inserting elements at the end of an array
<code>$arr = array();
array_push($arr, e1, e2, ... , en);
</code>3. array_splice() – inserting elements at any position (keys are reindexed)
<code>$fruits = array('apple','pear','banana','orange');
// third parameter is 0 (no removal), second parameter is the index, last parameter is the element or an array of elements
array_splice($fruits, 3, 0, 'pie');
pr($fruits);
</code>Output:
<code>Array(
[0] => apple
[1] => pear
[2] => banana
[3] => pie
[4] => orange
)
</code>Inserting multiple new elements can be done by passing an array:
<code>$fruits = array('apple','pear','banana','orange');
$new_items = array('pie','pie2');
array_splice($fruits, 3, 0, $new_items);
pr($fruits);
</code>Output:
<code>Array(
[0] => apple
[1] => pear
[2] => banana
[3] => pie
[4] => pie2
[5] => orange
)
</code>PHP Learning Recommendations
Vue3+Laravel8+Uniapp Beginner to Real‑World Development Tutorial
Vue3+TP6+API Social E‑Commerce System Development Course
Swoole From Beginner to Advanced – Recommended Course
Workerman+TP6 Real‑Time Chat System – Limited Time Offer
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.