PHP

PHP Menu

PHP

array_slice() Function - Definition, Syntax, Parameters, Examples

Definition

The array_slice() function returns selected parts of an array. If the array have string keys, the returned array will always preserve the keys.

Syntax

array_slice(array, start, length, preserve)

Parameters

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. Specifies if the function should preserve or reset the keys. Possible values: true - Preserve keys; false - Default. Reset keys

Example

<?php
// Example 1 $ages = array("Mark" => 22, "Jeff" => 32, "Mike" => 28); print_r(array_slice($ages, 1)); echo "<br>";
// Example 2 $cities = array("New York", "Salt Lake", "Tokyo", "Berlin", "London"); print_r(array_slice($cities, 1, 2)); echo "<br>";
// Example 3 print_r(array_slice($cities, -1, 1)); echo "<br>";
// Example 4 print_r(array_slice($cities, 1, 2, true)); echo "<br>";

Introduction

PHP Basics

PHP Advance

PHP OOP

PHP Functions and Methods