Retrieving Collection Parts
Sometimes you do not need a whole array. You need a part of it: a range of elements, the first or last few, pieces of equal size, or a moving window of neighbours.
The workhorse for this in PHP is array_slice. array_slice($words, $offset, $length) gives $length elements, starting at index $offset. The second number is a count of elements, not an end index. Leave out $length to go to the end. A negative $offset counts back from the end, and a negative $length stops that many elements before the end.
array_slice($s, $i, $n)—$nelements, starting at index$iarray_slice($s, 0, $n)— the first$nelementsarray_slice($s, $i)— everything from index$ito the endarray_slice($s, -$n)— the last$nelementsarray_slice($s, 0, -$n)— everything except the last$nelements
array_slice always builds a new array and copies the chosen elements into it. Changing the copy does not change the original, and changing the original does not change the copy. In some other languages the same operation gives a view that shares memory with the original — in PHP it never does.
For pieces of equal size PHP has a second ready-made function, array_chunk. For the jobs neither function can do on its own, this lesson uses a for or foreach loop and a small helper function or two.
Most examples on this page use the same data: the words one two three four five six.
Slice
Slicing means taking the elements at some chosen positions.
For a run of neighbouring positions, use array_slice: array_slice($words, 1, 3) gives the elements at indexes 1, 2 and 3. Careful: the 3 is a length, not an end index — start at index 1 and take 3 elements.
array_slice cannot skip elements. To take every second element, use a for loop with $i += 2. For positions you list yourself, in your own order, array_map over an array of indexes picks the element at each one.
Slice a range
array_slice($words, 1, 3) starts at index 1 and takes 3 elements: the words at indexes 1, 2 and 3. The result is a new array, so a change to it would not touch $words. The program prints two, three, four.
Output: PHP script
<?php
$words = ["one", "two", "three", "four", "five", "six"];
// offset 1, length 3: the elements at indexes 1, 2 and 3
$part = array_slice($words, 1, 3);
echo implode(", ", $part), "\n";
Slice with a step
To take every second element, a for loop with $i += 2 visits indexes 0, 2 and 4 and collects the words. $part[] = ... appends an element to the end of an array.
Output: PHP script
<?php
$words = ["one", "two", "three", "four", "five", "six"];
// take every second element from index 0 up to index 4
$part = [];
for ($i = 0; $i <= 4; $i += 2) {
$part[] = $words[$i];
}
echo implode(", ", $part), "\n";
Slice by a list of indices
The positions 3, 5 and 0 are stored in an array of numbers. array_map looks up $words[$i] for each one, so the result comes out in the order of the indices: four, six, one.
Output: PHP script
<?php
$words = ["one", "two", "three", "four", "five", "six"];
$indices = [3, 5, 0];
// pick the element at each position, in that order
$part = array_map(fn($i) => $words[$i], $indices);
echo implode(", ", $part), "\n";
Take and Drop
Take means keep a number of elements from one end. Drop means throw away a number of elements from one end and keep the rest.
Both are calls to array_slice in PHP. array_slice($words, 0, 3) takes the first 3 elements and array_slice($words, -3) takes the last 3 — a negative offset counts back from the end. array_slice($words, 1) drops the first element and array_slice($words, 0, -5) drops the last 5, because a negative length stops that many elements before the end.
There are also conditional versions: takeWhile, takeLastWhile, dropWhile and dropLastWhile. These do not count elements. They walk from one end and stop at the first element that fails a condition. PHP has no built-in versions, so a small helper function with a foreach loop does the job — and the Last variants simply reverse the array with array_reverse, run the same helper, and reverse the result back.
Take the first or last n elements
array_slice($words, 0, 3) keeps the first 3 words. array_slice($words, -3) keeps the last 3, because a negative offset counts back from the end.
Output: PHP script
<?php
$words = ["one", "two", "three", "four", "five", "six"];
$first3 = array_slice($words, 0, 3); // the first 3 elements
$last3 = array_slice($words, -3); // the last 3 elements
echo implode(", ", $first3), "\n";
echo implode(", ", $last3), "\n";
Drop the first or last n elements
array_slice($words, 1) skips the first word and keeps the rest. array_slice($words, 0, -5) stops 5 elements before the end, so only one is left.
Output: PHP script
<?php
$words = ["one", "two", "three", "four", "five", "six"];
$withoutFirst = array_slice($words, 1); // drop the first element
$withoutLast5 = array_slice($words, 0, -5); // drop the last 5 elements
echo implode(", ", $withoutFirst), "\n";
echo implode(", ", $withoutLast5), "\n";
Take while a condition holds
takeWhile keeps words from the start until it meets a word that starts with f. str_starts_with() checks the start of a string. takeLastWhile keeps words from the end until it meets three: it reverses the array with array_reverse, runs takeWhile, and reverses the result back.
Output: PHP script
<?php
// takeWhile keeps elements from the start while $keep says yes, then stops.
function takeWhile(array $items, callable $keep): array {
$result = [];
foreach ($items as $item) {
if (!$keep($item)) {
break;
}
$result[] = $item;
}
return $result;
}
// takeLastWhile does the same from the end: reverse, take, reverse back.
function takeLastWhile(array $items, callable $keep): array {
return array_reverse(takeWhile(array_reverse($items), $keep));
}
$words = ["one", "two", "three", "four", "five", "six"];
$fromStart = takeWhile($words, fn($w) => !str_starts_with($w, "f"));
$fromEnd = takeLastWhile($words, fn($w) => $w !== "three");
echo implode(", ", $fromStart), "\n";
echo implode(", ", $fromEnd), "\n";
Drop while a condition holds
dropWhile skips the 3-letter words at the start and keeps everything from three on. dropLastWhile skips words from the end while they contain the letter i. str_contains() checks whether a string holds a piece of text.
Output: PHP script
<?php
// dropWhile skips elements from the start while $skip says yes, and keeps the rest.
function dropWhile(array $items, callable $skip): array {
$result = [];
$dropping = true;
foreach ($items as $item) {
if ($dropping && $skip($item)) {
continue;
}
$dropping = false;
$result[] = $item;
}
return $result;
}
// dropLastWhile does the same from the end: reverse, drop, reverse back.
function dropLastWhile(array $items, callable $skip): array {
return array_reverse(dropWhile(array_reverse($items), $skip));
}
$words = ["one", "two", "three", "four", "five", "six"];
$fromStart = dropWhile($words, fn($w) => strlen($w) === 3);
$fromEnd = dropLastWhile($words, fn($w) => str_contains($w, "i"));
echo implode(", ", $fromStart), "\n";
echo implode(", ", $fromEnd), "\n";
Chunked
Chunking means cutting an array into pieces of the same size. The last piece may be shorter when the elements do not divide evenly.
PHP has this built in: array_chunk($numbers, 3) returns an array of arrays, and the short last piece comes out right on its own. Because the result is nested, json_encode prints it with every piece in its own brackets: [[0,1,2],[3,4,5],…].
To work on each piece right away, hand the chunks to array_map: passing the name of a built-in function as a string, like 'array_sum', works just as well as an arrow function.
Split into chunks of 3
The numbers 0 to 13 are cut into pieces of 3 with a single call to array_chunk. The last piece has only 2 elements: [12,13].
Output: PHP script
<?php
$numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
// array_chunk cuts the array into pieces of 3; the last piece is shorter
$chunks = array_chunk($numbers, 3);
echo json_encode($chunks), "\n";
Sum each chunk
The same chunks, but each one is added up with the built-in array_sum. Its name is passed to array_map as a string. Only the sums are kept: 3, 12, 21, 30, 25.
Output: PHP script
<?php
$numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
// add up each chunk of 3 with array_sum; only the sums are kept
$sums = array_map('array_sum', array_chunk($numbers, 3));
echo implode(", ", $sums), "\n";
Windowed
A window is a group of neighbouring elements. Windowing slides the group along the array and collects every position. Unlike chunks, windows overlap.
PHP has no built-in windowed. A for loop that calls array_slice($items, $i, $size) at each position does it, and a small windowed helper makes it reusable. With a $step, the window moves several positions at a time. With $partial set to true, a shorter window at the end is kept instead of being thrown away.
A window of 2 that moves 1 step is the same as pairing each element with the next one. In PHP, array_map with null as the function glues two arrays together element by element — feed it the array without its last element and the array without its first, and you get the neighbour pairs.
Windows of 3
The window has 3 words and moves 1 position each time. The loop stops when a full window no longer fits, so there are 3 windows. The result is an array of arrays, printed with json_encode.
Output: PHP script
<?php
// windowed returns every group of $size elements, moving one position at a time.
function windowed(array $items, int $size): array {
$result = [];
for ($i = 0; $i + $size <= count($items); $i++) {
$result[] = array_slice($items, $i, $size);
}
return $result;
}
$words = ["one", "two", "three", "four", "five"];
echo json_encode(windowed($words, 3)), "\n";
Windows with a step and partial windows
The window has 3 numbers and moves 2 positions each time. Because $partial is true, the last window [9,10] is kept even though it is short.
Output: PHP script
<?php
// windowed returns groups of $size elements, moving $step positions each time.
// With $partial = true, a shorter group at the end is kept too.
function windowed(array $items, int $size, int $step = 1, bool $partial = false): array {
$result = [];
for ($i = 0; $i < count($items); $i += $step) {
$window = array_slice($items, $i, $size);
if (count($window) < $size && !$partial) {
break;
}
$result[] = $window;
}
return $result;
}
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
echo json_encode(windowed($numbers, 3, 2, true)), "\n";
Sum each window
Every window of 3 neighbours is cut out with array_slice and added up with array_sum. Only the sums are kept: 6, 9, 12.
Output: PHP script
<?php
$numbers = [1, 2, 3, 4, 5];
// add up every window of 3 neighbours
$sums = [];
for ($i = 0; $i + 3 <= count($numbers); $i++) {
$sums[] = array_sum(array_slice($numbers, $i, 3));
}
echo implode(", ", $sums), "\n";
Pair each element with the next one
array_map(null, ...) pairs each word with its neighbour: the first argument array misses the last element, the second misses the first, so the arrays line up as neighbours. The second loop compares the same neighbours and records whether the first word is longer than the second; json_encode prints the booleans as true and false.
Output: PHP script
<?php
$letters = ["one", "two", "three", "four", "five"];
// array_map with null glues the two arrays element by element:
// each element, paired with the one after it
$pairs = array_map(null, array_slice($letters, 0, -1), array_slice($letters, 1));
echo json_encode($pairs), "\n";
// the same walk, but compare the lengths of the neighbours
$longer = [];
for ($i = 0; $i + 1 < count($letters); $i++) {
$longer[] = strlen($letters[$i]) > strlen($letters[$i + 1]);
}
echo json_encode($longer), "\n";