PHP Array Functions II
Now let's explore array functions that modify arrays - adding, removing, merging, slicing, and restructuring elements. These functions are essential for dynamic data manipulation.
Adding Elements
| Function | Where | Returns |
|---|---|---|
array_push($arr, $val) |
End of array | New length |
$arr[] = $val |
End of array | - |
array_unshift($arr, $val) |
Beginning of array | New length |
<?php
$stack = ["A", "B"];
// Add to end
array_push($stack, "C", "D"); // ["A", "B", "C", "D"]
// Shorthand (single element)
$stack[] = "E"; // ["A", "B", "C", "D", "E"]
// Add to beginning
array_unshift($stack, "Z"); // ["Z", "A", "B", "C", "D", "E"]
?>
Output
Click Run to execute your code
Performance: Use
$arr[] = $val instead of
array_push() for single elements - it's faster!
Removing Elements
| Function | From | Returns |
|---|---|---|
array_pop($arr) |
End of array | Removed element |
array_shift($arr) |
Beginning of array | Removed element |
unset($arr[$key]) |
Specific key | - |
<?php
$queue = ["First", "Second", "Third", "Fourth"];
// Remove from end
$last = array_pop($queue);
echo $last; // "Fourth"
// $queue: ["First", "Second", "Third"]
// Remove from beginning
$first = array_shift($queue);
echo $first; // "First"
// $queue: ["Second", "Third"]
// Remove specific element
unset($queue[0]);
// $queue: [1 => "Third"] - Note: doesn't reindex!
// Reindex after unset
$queue = array_values($queue);
// $queue: [0 => "Third"]
?>
Merging Arrays
array_merge()
<?php
// Indexed arrays - concatenates
$a = [1, 2, 3];
$b = [4, 5, 6];
$merged = array_merge($a, $b); // [1, 2, 3, 4, 5, 6]
// Associative arrays - later values overwrite
$defaults = ["color" => "red", "size" => "M"];
$custom = ["size" => "L", "qty" => 2];
$config = array_merge($defaults, $custom);
// ["color" => "red", "size" => "L", "qty" => 2]
?>
Spread Operator (PHP 7.4+)
<?php
$first = [1, 2, 3];
$second = [4, 5, 6];
// Combine with spread
$all = [...$first, ...$second]; // [1, 2, 3, 4, 5, 6]
// Insert in middle
$middle = [...$first, "X", ...$second];
// [1, 2, 3, "X", 4, 5, 6]
?>
array_combine()
Create an associative array from two arrays:
<?php
$headers = ["Name", "Email", "Age"];
$values = ["John", "[email protected]", 30];
$row = array_combine($headers, $values);
// ["Name" => "John", "Email" => "[email protected]", "Age" => 30]
// Useful for CSV processing
$csvHeader = ["id", "product", "price"];
$csvRow = ["101", "Widget", "29.99"];
$record = array_combine($csvHeader, $csvRow);
?>
Slicing Arrays
array_slice()
Extract a portion without modifying original:
<?php
$arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// slice(offset, length)
array_slice($arr, 2, 4); // [2, 3, 4, 5]
array_slice($arr, 5); // [5, 6, 7, 8, 9]
array_slice($arr, -3); // [7, 8, 9]
array_slice($arr, 0, -2); // [0, 1, 2, 3, 4, 5, 6, 7]
array_slice($arr, 2, -2); // [2, 3, 4, 5, 6, 7]
// Preserve keys
$assoc = ["a" => 1, "b" => 2, "c" => 3];
array_slice($assoc, 1, 2, true); // ["b" => 2, "c" => 3]
?>
array_splice()
Remove/replace portion AND modify original:
<?php
// Remove elements
$arr = ["a", "b", "c", "d", "e"];
$removed = array_splice($arr, 2, 2); // Remove 2 at index 2
// $removed: ["c", "d"]
// $arr: ["a", "b", "e"]
// Replace elements
$arr = ["a", "b", "c", "d", "e"];
array_splice($arr, 1, 2, ["X", "Y", "Z"]);
// $arr: ["a", "X", "Y", "Z", "d", "e"]
// Insert elements (length = 0)
$arr = ["a", "b", "e"];
array_splice($arr, 2, 0, ["c", "d"]);
// $arr: ["a", "b", "c", "d", "e"]
?>
Other Useful Functions
<?php
// array_flip - Swap keys and values
$arr = ["a" => 1, "b" => 2, "c" => 3];
array_flip($arr); // [1 => "a", 2 => "b", 3 => "c"]
// array_reverse - Reverse order
$arr = [1, 2, 3, 4, 5];
array_reverse($arr); // [5, 4, 3, 2, 1]
// array_chunk - Split into chunks
$arr = [1, 2, 3, 4, 5, 6, 7];
array_chunk($arr, 3);
// [[1, 2, 3], [4, 5, 6], [7]]
// array_pad - Pad to specified length
$arr = [1, 2, 3];
array_pad($arr, 5, 0); // [1, 2, 3, 0, 0]
array_pad($arr, -5, 0); // [0, 0, 1, 2, 3]
// array_fill_keys - Create with same value
$keys = ["a", "b", "c"];
array_fill_keys($keys, 0); // ["a" => 0, "b" => 0, "c" => 0]
?>
Quick Reference
| Task | Function |
|---|---|
| Add to end | array_push() or $arr[] |
| Add to beginning | array_unshift() |
| Remove from end | array_pop() |
| Remove from beginning | array_shift() |
| Merge arrays | array_merge() |
| Create from keys/values | array_combine() |
| Extract portion | array_slice() |
| Remove/insert in place | array_splice() |
| Reverse order | array_reverse() |
| Split into chunks | array_chunk() |
Exercise: Playlist Manager
Task: Create a playlist manager with array functions.
Requirements:
- Add songs to end of playlist
- Add song to beginning (play next)
- Remove currently playing song (first)
- Move a song to a different position
- Merge two playlists
Show Solution
<?php
class Playlist {
private $songs = [];
// Add to end
public function add($song) {
$this->songs[] = $song;
}
// Add to beginning (play next)
public function playNext($song) {
array_unshift($this->songs, $song);
}
// Remove current (first song)
public function skipCurrent() {
return array_shift($this->songs);
}
// Move song to new position
public function moveSong($fromIndex, $toIndex) {
$song = array_splice($this->songs, $fromIndex, 1);
array_splice($this->songs, $toIndex, 0, $song);
}
// Merge another playlist
public function merge($otherSongs) {
$this->songs = array_merge($this->songs, $otherSongs);
}
public function show() {
foreach ($this->songs as $i => $song) {
echo ($i + 1) . ". $song\n";
}
}
}
$playlist = new Playlist();
$playlist->add("Song A");
$playlist->add("Song B");
$playlist->add("Song C");
echo "Initial playlist:\n";
$playlist->show();
$playlist->playNext("Urgent Song");
echo "\nAfter playNext:\n";
$playlist->show();
$skipped = $playlist->skipCurrent();
echo "\nSkipped: $skipped\n";
$playlist->show();
$playlist->merge(["Song X", "Song Y"]);
echo "\nAfter merge:\n";
$playlist->show();
?>
Summary
- Adding:
array_push(),array_unshift(),$arr[] - Removing:
array_pop(),array_shift(),unset() - Merging:
array_merge()or spread... - Slicing:
array_slice()(non-destructive) - Splicing:
array_splice()(destructive) - Use spread: For clean, readable array merging
- Remember:
unset()doesn't reindex!
What's Next?
Now let's explore Array Iteration - powerful functions like
array_map(), array_filter(), and array_reduce()
for functional-style array processing!
Enjoying these tutorials?