🎓 A1Learner
🔍
0 of 38 lessons completed

Slices and Merges

Slicing cuts a piece out of an array, and merging joins two arrays into one. One cut function leaves the array alone, and the other one changes the array itself.

array_slice takes a middle piece

The slice starts at index 1 and takes three values. The second print shows the original array still whole.

<?php
$letters = ["a", "b", "c", "d", "e"];
$middle = array_slice($letters, 1, 3);
print_r($middle);
print_r($letters);

array_splice replaces a piece in place

The splice starts at index 1 and removes two values. The two new values land in the gap, and the array itself carries the change.

<?php
$letters = ["a", "b", "c", "d"];
array_splice($letters, 1, 2, ["x", "y"]);
print_r($letters);

array_merge renumbers, + keeps the left

Both arrays share the key 1 here. array_merge renumbers every number key, while the + operator keeps the left value for the shared key.

<?php
$first = [1 => "pen", 2 => "book"];
$second = [1 => "bag", 3 => "ruler"];
print_r(array_merge($first, $second));
print_r($first + $second);

array_chunk splits into pairs

The chunk size is 2 here. Six numbers come back as three small arrays of two numbers each.

<?php
$numbers = [1, 2, 3, 4, 5, 6];
$pairs = array_chunk($numbers, 2);
print_r($pairs);

Example

<?php
$songs = ["Intro", "Verse", "Chorus", "Bridge", "Outro"];
$middle = array_slice($songs, 1, 3);
print_r($middle);
array_splice($songs, 0, 1, ["Opening"]);
print_r($songs);
print_r(array_chunk($songs, 2));

Key points

  • array_slice hands back a piece of an array and leaves the given array unchanged.
  • array_splice cuts a piece out of the given array and can drop new values into the gap.
  • The start and length numbers in both functions count places in the array.
  • array_merge joins two arrays and renumbers the number keys.
  • The + operator joins two arrays and keeps the left value when both arrays share a key.
  • array_chunk splits an array into smaller arrays of a chosen size.

In this example, a playlist of five songs is edited three ways. array_slice first copies out the middle three songs and the playlist stays whole. array_splice then swaps the first song for Opening inside the playlist itself. array_chunk at the end splits the edited playlist into pairs, and the last pair holds the one song left over.

Note

array_splice changes the array it is given, while array_slice leaves its array unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Two arrays share the key 1. Which join keeps the left value for that key?