Slicing/Extracting arrays with array_slice()

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters. array_slice() enables you to extract a chunk of an array. It accepts an array as an argument, a starting position (offset), and a length (optional). If the length is omitted, array_slice() returns all elements from the starting position onward. array_slice() does not alter the array you pass to it; it returns a new array containing the elements needed.

Example code:

<?php
$alpha = array ("a", "b", "c", "d", "e", "f");
$second = array_slice($first, 2, 3);
 
foreach ( $second as $var ) {
  print "$var<br />";
}

This prints the elements ‘c’, ‘d’, and ‘e’. The offset is inclusive in the returning of elements.

If the offset argument is less than zero, the returned slice returns that number of elements from the end of the given array.

If the length argument is less than zero, the returned slice contains all elements from the offset position to that number of elements from the end of the given array.

Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

 

 
eXTReMe Tracker