How to cut out array elements into a new array?

PHP array_slice() function

PHP array_slice() is an inbuilt array function that is used to cut out or extract a specific part of elements of an array into a new array.

Syntax of the array_slice function

array_slice(array, start, length, preserve_keys);
  • array (Required) – The array whose elements you want to extract.
  • start (Required) – This parameter takes the position number of the element from where you want to start extracting.
  • length (Optional) – The length defines how many elements you want to extract from the starting number. If you don’t define this, it will extract all elements from starting position to the end of the array.
  • preserve_keys (Optional) – By default it is FALSE, but if you want to preserve the same keys of the elements into the new array, then pass TRUE.

Example of the array_slice function

<?php
//            0         1        2        3          4
$fruits = ['Apple', 'Banana', 'Mango', 'Orange', 'Pineapple'];
$array = array_slice($fruits, 2);
print_r($array);
Array
(
    [0] => Mango    
    [1] => Orange   
    [2] => Pineapple
)

Length parameter example

<?php
//            0         1        2        3          4
$fruits = ['Apple', 'Banana', 'Mango', 'Orange', 'Pineapple'];
$array = array_slice($fruits, 2, 2);
print_r($array);
Array
(
    [0] => Mango 
    [1] => Orange
)

Preserve_keys Example

<?php
//            0         1        2        3          4
$fruits = ['Apple', 'Banana', 'Mango', 'Orange', 'Pineapple'];
$array = array_slice($fruits, 2, 2, TRUE);
print_r($array);
(
    [2] => Mango 
    [3] => Orange
)

Negative Number Example

You can also use a negative number to define the starting position.

<?php
//           -5       -4        -3        -2         -1
$fruits = ['Apple', 'Banana', 'Mango', 'Orange', 'Pineapple'];
$array = array_slice($fruits, -4, 3);
print_r($array);
Array
(
    [1] => Banana
    [2] => Mango 
    [3] => Orange
)

Leave a Reply