• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Arrays / Extracting Elements from PHP Arrays with array_slice()

Extracting Elements from PHP Arrays with array_slice()

30 March 2010 / Leave a Comment

In Working With Array Elements in PHP, you saw how to read and change individual elements within a PHP array. However, sometimes it’s useful to work with a range of array elements. For example, you may want to work with a large array in chunks, or sort an array then retrieve just the “top 10” values from the start of the array.

In this tutorial you’ll explore PHP’s array_slice() function for extracting a range of elements from an array.

Basic array_slice() usage

To use array_slice(), you typically pass it the following arguments:

  • The array to extract the slice from.
  • The position of the element where you want to start the extraction (the first element has a position of 0).
  • The number of elements to extract.

array_slice() then returns an array containing the extracted elements. (The original array is not modified.)

Here’s an example showing how to use array_slice():


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Array ( [0] => Stanley Kubrick [1] => Martin Scorsese )"
print_r( array_slice( $directors, 1, 2 ) );

The above code creates a 4-element array of director names, then uses array_slice() to extract the second and third elements.

Note that the position of an element is not necessarily the same as its index. For example, the first element in an array always has a position of 0, but its index might be 456. Indexed arrays in PHP do not have to have contiguous indices starting from zero (although they often do).

Preserving indices

You can see from the above example that array_slice() re-indexes the elements in the resulting array: Stanley Kubrick gets a new index of 0, while Martin Scorsese gets a new index of 1. Often this isn’t a problem, since you only care about the order of the elements in the resulting slice, not their indices.

However, sometimes it’s important to retain the indices of the extracted elements. For example, the indices might be keys that point to records in a database table, or they might have some other significance. In this situation, you can preserve the indices of the extracted elements by passing a fourth argument of true to array_slice(). Here’s an example:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Array ( [1] => Stanley Kubrick [2] => Martin Scorsese )"
print_r( array_slice( $directors, 1, 2, true ) );

Notice that array_slice() has now preserved the indices from the original array: 1 for Stanley Kubrick, and 2 for Martin Scorsese.

array_slice() always preserves indices in associative arrays, as you’ll see in a moment. So there’s no need to pass the true argument when slicing associative arrays.

Extracting to the end of an array

If you leave out the third argument then array_slice() extracts from the starting position all the way to the end of the array. This can be useful when you don’t know how long the array is. For example:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Array ( [0] => Stanley Kubrick [1] => Martin Scorsese [2] => Fritz Lang )"
print_r( array_slice( $directors, 1 ) );

Using array_slice() on associative arrays

You can also use array_slice() to extract elements from an associative array. Here’s an example that retrieves 2 elements from an associative array, starting at the second element:


$movie = array( "title" => "Rear Window",
                "director" => "Alfred Hitchcock",
                "year" => 1954, 
                "minutes" => 112 );

// Displays "Array ( [director] => Alfred Hitchcock [year] => 1954 )"
print_r( array_slice( $movie, 1, 2 ) );

Notice that, in the above example, array_slice() preserves the "director" and "year" indices in the resulting array.

Summary

In this article you’ve explored array_slice(), a handy PHP function that returns a range of elements in an array. You’ve seen how to:

  • Use array_slice() with both indexed and associative arrays
  • Preserve indices when working with indexed arrays, and
  • Extract elements all the way up to the end of an array.

Happy coding!

Filed Under: PHP Arrays Tagged With: array_slice, associative, extract to end of array, indexed, php arrays, preserve indices

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits