← Back to PHP Course | Chapter 7: Arrays | Lesson 13 of 13

PHP Array Manipulation

Adding and Removing from Ends

array_push() and array_pop() add and remove elements from the end of an array respectively, giving you a simple way to use a PHP array as a stack when you need last-in-first-out behavior.

Example: Adding and Removing from Ends

php
<?php
$stack = [1, 2];
array_push($stack, 3);
array_pop($stack);
print_r($stack);
?>

Adding and Removing from Beginning

array_shift() and array_unshift() do the same at the beginning of an array instead of the end, but note they also reindex all the existing numeric keys, which can be an expensive operation on large arrays.

Example: Adding and Removing from Beginning

php
<?php
$queue = [2, 3];
array_unshift($queue, 1);
array_shift($queue);
print_r($queue);
?>

Slicing Arrays

array_slice() extracts a portion of an array without modifying the original, while array_splice() removes and optionally replaces a portion in place — mixing these two up is a common source of unexpected side effects.

Example: Slicing Arrays

php
<?php
$arr = [1, 2, 3, 4, 5];
$slice = array_slice($arr, 1, 2);
print_r($slice);
print_r($arr); // unchanged
?>

Splicing Arrays

array_merge() combines two or more arrays into one, with later arrays overwriting earlier ones on matching string keys but simply appending and renumbering on matching numeric keys — a distinction worth testing carefully.

Example: Splicing Arrays

php
<?php
$arr1 = ["a" => 1, "b" => 2];
$arr2 = ["b" => 3, "c" => 4];
print_r(array_merge($arr1, $arr2));
?>

Removing Duplicate Elements

unset($array[$key]) removes a single element by key without reindexing the remaining numeric keys, leaving a gap — if you need a clean, renumbered list afterward, follow it with array_values().

Example: Removing Duplicate Elements

php
<?php
$arr = [10, 20, 30];
unset($arr[1]);
print_r($arr);
print_r(array_values($arr));
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.