array_slice()
5th June 2020
0 Comments
Programming Language
PHP [Versions: 4, 5, 7]
Syntax
Typical Usage
Setting a limit and/or an offset on an array to extract a slice of the array. Works similar to an SQL statement that limits and offsets the data pulled from a database.
Accepted Parameters
- array (array) (Required): The array you wish to slice.
- offset (integer) (Required): If the offset is non-negative, the sequence will start at that offset in the array. If the offset is negative, the sequence will start that far from the end of the array.
- limit (integer) (Required): If length is given and is positive, then the sequence will have up to that many elements in it.
- preserve_keys (boolean) (Optional, Default = false): If preserve_keys is false or left blank, arrays with integer keys will be reset to the default 0, 1, 2 etc…. String keys will always remain intact regardless of this setting.
Notes
- The offset parameter refers to the position in the array, not the key.
- array_slice() will reorder and reset arrays with integer indices by default. To override this, set preserve_keys to true.
Examples of array_slice()
Example 1
<?php
$products = array (
'spoon',
'fork',
'knife',
'plate',
'cup',
'jug'
);
array_slice ( $products, 2, 4 );
Output
Array (
[0] => fork
[1] => knife
[2] => plate
[3] => cup
)
Example 2
<?php
$products = array (
'spoon',
'fork',
'knife',
'plate',
'cup',
'jug'
);
array_slice ( $products, 1, 4, true );
Output
Array (
[1] => fork
[2] => knife
[3] => plate
[4] => cup
)
Example 3 (Associative Array)
<?php
$products = array (
'kitchenware' => array(
'spoon',
'fork',
'knife',
'plate',
'cup',
'jug'
),
'tools' => array(
'spanner',
'screwdriver',
'hammer',
'spade'
),
'bedding' => array(
'pillow',
'blanket',
'duvet'
),
'tech' => array(
'monitor',
'usb',
'tv'
),
);
array_slice ( $products, 1, 2 );
Output
Array (
[tools] => Array (
spanner
screwdriver
hammer
spade
)
[bedding] => Array (
pillow
blanket
duvet
)
)
The above will output the same whether the third parameter (preserve_keys) is true or false.
Used In Projects
Was This Helpful?
If this post has helped you, please let me know. Your feedback will be highly appreciated and will help me build better content.