Arrays change often. PHP has a function for every common change.
| Task | Tool |
|---|---|
| Add to the end | $arr[] = $x or array_push() |
| Remove from the end | array_pop() |
| Add to the start | array_unshift() |
| Remove from the start | array_shift() |
| Remove any item | unset() or array_splice() |
Add to the end
<?php
$stack = ["a", "b"];
$stack[] = "c"; // the simple way
array_push($stack, "d", "e"); // several at once
echo implode(", ", $stack);
a, b, c, d, e
Remove from the end
array_pop() removes the last item and returns it.
<?php
$stack = ["a", "b", "c"];
$last = array_pop($stack);
echo "$last removed, left: " . implode(", ", $stack);
c removed, left: a, b
Add to and remove from the start
<?php
$queue = ["b", "c"];
array_unshift($queue, "a"); // add at the start
$first = array_shift($queue); // remove from the start
echo "$first | " . implode(", ", $queue);
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.
<?php
$colors = ["red", "green", "blue"];
unset($colors[1]);
print_r($colors);
Array
(
[0] => red
[2] => blue
)
To get a clean list again, use array_values().
<?php
$colors = ["red", "green", "blue"];
unset($colors[1]);
$colors = array_values($colors);
print_r($colors);
Array
(
[0] => red
[1] => blue
)
array_splice(): insert or remove in the middle
<?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);
a, d
a, x, y, d
Remove by value
<?php
$tags = ["php", "web", "php", "css"];
$tags = array_diff($tags, ["php"]);
echo implode(", ", $tags);
web, css
Empty an array
<?php
$list = [1, 2, 3];
$list = [];
echo count($list);
0
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.