Skip to content

PHP Tutorial Arrays

Adding and Removing Items

Lesson 121 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Arrays change often. PHP has a function for every common change.

TaskTool
Add to the end$arr[] = $x or array_push()
Remove from the endarray_pop()
Add to the startarray_unshift()
Remove from the startarray_shift()
Remove any itemunset() or array_splice()

Add to the end

index.php
PHP
<?php
$stack = ["a", "b"];

$stack[] = "c";                 // the simple way
array_push($stack, "d", "e");   // several at once

echo implode(", ", $stack);
Output
OUTPUT
a, b, c, d, e

Remove from the end

array_pop() removes the last item and returns it.

index.php
PHP
<?php
$stack = ["a", "b", "c"];

$last = array_pop($stack);

echo "$last removed, left: " . implode(", ", $stack);
Output
OUTPUT
c removed, left: a, b

Add to and remove from the start

index.php
PHP
<?php
$queue = ["b", "c"];

array_unshift($queue, "a");   // add at the start
$first = array_shift($queue); // remove from the start

echo "$first | " . implode(", ", $queue);
Output
OUTPUT
a | b, c

array_shift() and array_unshift() re-number the keys of a list, so they are slower on very large arrays.

Remove a specific item with unset()

unset() removes the item, but it does not re-number the keys.

index.php
PHP
<?php
$colors = ["red", "green", "blue"];

unset($colors[1]);

print_r($colors);
Output
OUTPUT
Array
(
    [0] => red
    [2] => blue
)

To get a clean list again, use array_values().

index.php
PHP
<?php
$colors = ["red", "green", "blue"];

unset($colors[1]);
$colors = array_values($colors);

print_r($colors);
Output
OUTPUT
Array
(
    [0] => red
    [1] => blue
)

array_splice(): insert or remove in the middle

index.php
PHP
<?php
$letters = ["a", "b", "c", "d"];

array_splice($letters, 1, 2);            // remove 2 items from position 1
echo implode(", ", $letters) . "\n";

array_splice($letters, 1, 0, ["x", "y"]); // insert at position 1
echo implode(", ", $letters);
Output
OUTPUT
a, d
a, x, y, d

Remove by value

index.php
PHP
<?php
$tags = ["php", "web", "php", "css"];

$tags = array_diff($tags, ["php"]);

echo implode(", ", $tags);
Output
OUTPUT
web, css

Empty an array

index.php
PHP
<?php
$list = [1, 2, 3];
$list = [];

echo count($list);
Output
OUTPUT
0
lightbulb
The short syntax is best
$array[] = $item; is faster and shorter than array_push($array, $item) for one item. Use array_push() only for several at once.