0

I have array:

array('a','b','c','d','e');

And I want to trim it to 3 elements, so we end up with:

array('a','b','c');

What's the best practice to achieve this with optimisation in mind? My arrays are massive.

What I've tried so far

  1. foreach() loop through array and store the first 3 elements.
  2. Count arrays and use array_pop().

I feel there is a standard function or approach to this.

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

2 Answers2

1

You can use array-slice, for example:

$data = array_slice($arr, 0, 3);
Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31
1

Haven't you tried

array_slice($input, 0, 3);

That is the easiest and the php's standard way

Rinsad Ahmed
  • 1,877
  • 1
  • 10
  • 28