Skip to main content

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) — $n elements, starting at index $i
  • array_slice($s, 0, $n) — the first $n elements
  • array_slice($s, $i) — everything from index $i to the end
  • array_slice($s, -$n) — the last $n elements
  • array_slice($s, 0, -$n) — everything except the last $n elements

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.

Prompt
Make an array of the words one, two, three, four, five, six. Use array_slice with offset 1 and length 3 to take the elements at indexes 1, 2 and 3. Print the result with implode.
Output: PHP script
Slice a range

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.

Prompt
Make an array of the words one, two, three, four, five, six. Use a for loop that goes from index 0 to index 4 in steps of 2 and appends each element to a new array. Print the result with implode.
Output: PHP script
Slice with a step

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.

Prompt
Make an array of the words one, two, three, four, five, six and an array of indices 3, 5, 0. Use array_map over the indices to collect the words at those positions, in that order. Print the result with implode.
Output: PHP script
Slice by a list of indices

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.

Prompt
Make an array of the words one, two, three, four, five, six. Use array_slice to get the first 3 elements and the last 3 elements. Print both results on separate lines with implode.
Output: PHP script
Take the first or last n elements

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.

Prompt
Make an array of the words one, two, three, four, five, six. Use array_slice to get everything except the first element, and everything except the last 5 elements. Print both results on separate lines with implode.
Output: PHP script
Drop the first or last n elements

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.

Prompt
Write takeWhile and takeLastWhile helper functions that take an array and a condition function. takeWhile keeps elements from the start while the condition holds; takeLastWhile does the same from the end by reversing the array, running takeWhile and reversing the result back. Use them on the words one, two, three, four, five, six: keep from the start while the word does not start with f, and keep from the end while the word is not three. Print both results.
Output: PHP script
Take while a condition holds

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.

Prompt
Write dropWhile and dropLastWhile helper functions that take an array and a condition function. dropWhile skips elements from the start while the condition holds and keeps the rest; dropLastWhile does the same from the end. Use them on the words one, two, three, four, five, six: skip from the start while the word has 3 letters, and skip from the end while the word contains the letter i. Print both results.
Output: PHP script
Drop while a condition holds

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].

Prompt
Make an array of the numbers 0 to 13. Use array_chunk to split it into pieces of 3 and print the result with json_encode.
Output: PHP script
Split into chunks of 3

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.

Prompt
Make an array of the numbers 0 to 13. Split it into pieces of 3 with array_chunk, add up each piece by mapping array_sum over the chunks, and print the array of sums with implode.
Output: PHP script
Sum each chunk

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.

Prompt
Write a windowed helper function that takes an array and a window size and returns every group of that many neighbouring elements, moving one position at a time. Use it with size 3 on the words one, two, three, four, five. Print the result with json_encode.
Output: PHP script
Windows of 3

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.

Prompt
Write a windowed helper that takes an array, a window size, a step and a partial flag. It moves step positions between windows, and when partial is true it also keeps a shorter window at the end. Use it on the numbers 1 to 10 with size 3, step 2 and partial set to true. Print the result with json_encode.
Output: PHP script
Windows with a step and partial windows

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.

Prompt
Make an array of the numbers 1 to 5. Loop over every window of 3 neighbouring elements, add up each window with array_sum and collect the sums. Print the array of sums with implode.
Output: PHP script
Sum each window

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.

Prompt
Make an array of the words one, two, three, four, five. Pair each element with the one after it using array_map with null over the array without its last element and the array without its first element, and print the array of pairs with json_encode. Then loop over the same neighbours and record whether the first word is longer than the second. Print the array of booleans with json_encode.
Output: PHP script
Pair each element with the next one