tmartin314
tmartin314

Reputation: 4171

PHP keep first 6 items in an array and drop the rest

I am wondering how I can drop any array items that come after a certain number like 6. Is there something in PHP that enables you do do it? Or is it a custom function that needs to be written

Upvotes: 0

Views: 449

Answers (2)

mfonda
mfonda

Reputation: 8003

If you're looking to take the first six elements of an array, based on position in the array, then array_slice or array_splice is the way to go.

array_splice($array, 6);

If you want to keep all elements with value less than 6, you could do something like:

$array = array_filter($array, function($v) { return $v <= 6; });

Upvotes: 1

John Parker
John Parker

Reputation: 54445

You could use array_slice for this purpose. For example:

$testArray = range(0, 10);

// Ensure there are at least six items in the source array.
if(count($testArray) >= 6) {
   // Grab the first six items.
   $firstSixItemsFromArray = array_slice($testArray, 0, 6);
}

Upvotes: 5

Related Questions