PHP array_slice examples

Last updated on October 21, 2022 A Goodman Loading... Post a comment

The array_slice() function (available since PHP 4) is used to extract a slice of a given array. It returns a new array that contains elements from the input array as specified by the start and length parameters.

array_slice(array, start, length, preserve)

If start is non-negative, the sequence will start at that offset in the array. On the other hand, if this value is negative, the sequence will start that far from the end of the array.

The boolean preserve parameter is optional. If it’s true, the keys from the input array will be preserved. If it’s false, these ones will be reset.

Examples

Example 1: Array with numeric keys

Code:

<?php
$arr_old = [
  0 => 'a',
  1 => 'b',
  2 => 'c',
  3 => 'd',
  4 => 'e',
  5 => 'f',
  6 => 'g'
];

$arr_new = array_slice($arr_old,2, 5);

// printing the output 
echo '<pre>';
print_r($arr_new);
echo '</pre>';

?>

Output:

Array
(
    [0] => c
    [1] => d
    [2] => e
    [3] => f
    [4] => g
)

Example 2: Array with string keys

Code:

<?php
$arr_old = [
  'father' => 'John',
  'mother' => 'Jin',
  'son' => 'Tom'
];

$arr_new = array_slice($arr_old, 1, 3);

// printing the output 
echo '<pre>';
print_r($arr_new);
echo '</pre>';
?>

Output:

Array
(
    [mother] => Jin
    [son] => Tom
)

Example 3: Offset is negative and keys are preserved

Code:

<?php
$arr_old = [
  0 => 'a',
  1 => 'b',
  2 => 'c',
  3 => 'd',
  4 => 'e',
  5 => 'f',
  6 => 'g'
];

$arr_new = array_slice($arr_old, -4, 2, true);

// printing the output 
echo '<pre>';
print_r($arr_new);
echo '</pre>';

?>

Output:

Array
(
    [3] => d
    [4] => e
)

Example 4: Multi-dimensional array

Code:

<?php
$arr_old = [
  [
    'name' => 'Ann',
    'age' => 33
  ],
  [
    'name' => 'Max',
    'age' => 11
  ],
  [
    'name' => 'John',
    'age' => 45
  ],
  [
    'name' => 'Trump',
    'age' => 5
  ]
];

$arr_new = array_slice($arr_old, 1, 3, true);

// printing the output 
echo '<pre>';
print_r($arr_new);
echo '</pre>';
?>

Output:

Array
(
    [1] => Array
        (
            [name] => Max
            [age] => 11
        )

    [2] => Array
        (
            [name] => John
            [age] => 45
        )

    [3] => Array
        (
            [name] => Trump
            [age] => 5
        )

)

You can find more detailed information about the array_slice function in the official docs.

Further reading:

I have made every effort to ensure that every piece of code in this article works properly, but I may have made some mistakes or omissions. If so, please send me an email: [email protected] or leave a comment to report errors.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles