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:
Array(
[0] => cherry
[1] => apple
[2] => pear
[3] => banana
[4] => orange
)array_unshift can also accept multiple elements:
$fruits = array('apple','pear','banana','orange');
array_unshift($fruits, 'cherry', 'pie');
pr($fruits);Output:
Array(
[0] => cherry
[1] => pie
[2] => apple
[3] => pear
[4] => banana
[5] => orange
)2. array_push() – inserting elements at the end of an array
$arr = array();
array_push($arr, e1, e2, ... , en);3. array_splice() – inserting elements at any position (keys are reindexed)
$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);Output:
Array(
[0] => apple
[1] => pear
[2] => banana
[3] => pie
[4] => orange
)Inserting multiple new elements can be done by passing an array:
$fruits = array('apple','pear','banana','orange');
$new_items = array('pie','pie2');
array_splice($fruits, 3, 0, $new_items);
pr($fruits);Output:
Array(
[0] => apple
[1] => pear
[2] => banana
[3] => pie
[4] => pie2
[5] => orange
)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
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
