In this tutorial, you shall learn how to truncate given array to a specific length in PHP using array_splice() function, with the help of example programs.

PHP – Truncate array

To truncate array or trim the end of array to specified length in PHP, we can use array_splice() function.

array_splice() function takes an array and a length as arguments, and truncates the given array to specified number of elements.

The syntax to call array_splice() function to truncate an array $arr to a length of $n is

array_splice($arr, $n)

Note: The function modifies the original array.



1. Truncate array to a length of 3

In this example, we take an array arr with five values. We truncate this array to a length of 3 using array_splice() function.

PHP Program

  $arr = ["apple", "banana", "cherry", "fig", "guava"];
  $n = 3;
  array_splice($arr, $n);


PHP - Truncate array


In this PHP Tutorial, we learned how to truncate an array to a specific length using array_splice() function.