PHP Array Manipulation
In this page:
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
$stack = [1, 2];
array_push($stack, 3);
array_pop($stack);
print_r($stack);
?>
Login to try C/C++/Java/PHP code in the editor
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
$queue = [2, 3];
array_unshift($queue, 1);
array_shift($queue);
print_r($queue);
?>
Login to try C/C++/Java/PHP code in the editor
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
$arr = [1, 2, 3, 4, 5];
$slice = array_slice($arr, 1, 2);
print_r($slice);
print_r($arr); // unchanged
?>
Login to try C/C++/Java/PHP code in the editor
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
$arr1 = ["a" => 1, "b" => 2];
$arr2 = ["b" => 3, "c" => 4];
print_r(array_merge($arr1, $arr2));
?>
Login to try C/C++/Java/PHP code in the editor
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
$arr = [10, 20, 30];
unset($arr[1]);
print_r($arr);
print_r(array_values($arr));
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: