W3Schools.com

PHP array_slice() Function


PHP Array Reference Complete PHP Array Reference

Definition and Usage

The array_slice() function returns selected parts of an array.

Syntax

array_slice(array,start,length,preserve)

Parameter Description
array Required. Specifies an array
start Required. Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array.
length Optional. Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
preserve Optional. Possible values:
  • true -  Preserve keys
  • false - Default - Reset keys



Tips and Notes

Note: If the array have string keys, the returned array will allways preserve the keys. (See example 4)


Example 1

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2));
?>

The output of the code above will be:

Array ( [0] => Cat [1] => Horse )


Example 2

With a negative start parameter:

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,-2,1));
?>

The output of the code above will be:

Array ( [0] => Horse )


Example 3

With the preserve parameter set to true:

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2,true));
?>

The output of the code above will be:

Array ( [1] => Cat [2] => Horse )


Example 4

With string keys:

<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse","d"=>"Bird");
print_r(array_slice($a,1,2));
?>

The output of the code above will be:

Array ( [b] => Cat [c] => Horse )


PHP Array Reference Complete PHP Array Reference
WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$3.98 Unlimited Hosting
Premium Website Design
WEB BUILDING
XML Editor - Free Trial!
FREE Website BUILDER
Best Website Templates Top CSS Templates
CREATE HTML Websites
EASY WEBSITE BUILDER
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE