PHP array_slice() Function
In this chapter you will learn:
- Definition for PHP array_slice() Function
- Syntax for PHP array_slice() Function
- Parameter for PHP array_slice() Function
- Example - slice from 2
- Example - Start the slice from from the second array element, and return only two elements
- Example - Using a negative start parameter
- Example - With the preserve parameter set to true
- Example - With both string and integer keys
Definition
The array_slice() function returns selected parts of an array.
Syntax
PHP array_slice() Function has the following syntax.
array_slice(array,start,length,preserve)
Parameter
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to slice |
start | Required. | Starting point. 0 = the first element. negative value mean to slice from last element. -2 means start at the second last element of the array. |
length | Optional. | length of the returned array. negative number means stop slicing that far from the last element. If not set, the function will return all elements, starting from start. |
preserve | Optional. | preserve or reset the keys. |
Possible values for preserve:
- true - Preserve keys
- false - Default. Reset keys
Example 1
<?php
$a=array("A","B","C","D","java2s.com");
print_r(array_slice($a,2));
?>
The code above generates the following result.
Example 2
Start the slice from from the second array element, and return only two elements:
<?php
$a=array("A","B","C","D","java2s.com");
print_r(array_slice($a,1,2));
?>
The code above generates the following result.
Example 3
Using a negative start parameter:
<?php
$a=array("A","B","C","D","java2s.com");
print_r(array_slice($a,-2,1));
?>
The code above generates the following result.
Example 4
With the preserve parameter set to true:
<?php
$a=array("A","B","C","D","java2s.com");
print_r(array_slice($a,1,2,true));
?>
The code above generates the following result.
Example 5
With both string and integer keys:
<?php//j av a 2s . com
$a=array("a"=>"Java","b"=>"PHP","c"=>"java2s.com","d"=>"HTML","e"=>"java2s.com");
print_r(array_slice($a,1,2));
$a=array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"java2s.com");
print_r(array_slice($a,1,2));
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_splice() Function
- Syntax for PHP array_splice() Function
- Parameter for PHP array_splice() Function
- Note for PHP array_splice() Function
- Example - Replace elements in an array
- Example - With the length parameter set to 0
- Example - inserts two new elements at the third position in the array
- Example - remove and insert elements at the same time
- Example - What happens if you omit the third argument
- Example - array_splice() automatically casts the fourth argument to an array before using it
Home » PHP Tutorial » PHP Array Functions