Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit Length of Array in PHP

Tags:

arrays

php

Is it possible to limit the number of members in an array, like LIMIT in MySQL? For instance, if I have $array with x members, and I only want to return the first 50 of them, how do I do that?

Should I use a combination of count() and array_slice(), or is there a simpler way?

like image 217
Alfo Avatar asked Jul 27 '12 14:07

Alfo


People also ask

How can I limit the size of an array in PHP?

To reduce an array, you can use array_splice( ): // no assignment to $array array_splice($array, 2); This removes all but the first two elements from $array.

How do you set limits in an array?

To limit array size with JavaScript, we can use the array slice method. to define the add function that takes an array a and value x that we prepend to the returned array. We keep the returned array the same size as a by calling slice with 0 and a. length - 1 to discard the last item in a .

Is there a limit to an array?

The maximum length of an array is 4,294,967,295 - that is, the maximum unsigned 32-bit integer.

What is the size of array in PHP?

There are two common ways to get the size of an array. The most popular way is to use the PHP count() function. As the function name says, count() will return a count of the elements of an array. But how we use the count() function depends on the array structure.


2 Answers

Using array_slice should do the trick.

array_slice($array, 0, 50); // same as offset 0 limit 50 in sql
like image 100
complex857 Avatar answered Oct 13 '22 10:10

complex857


Make sure $array is only 50 long:

array_splice($array, 50);

Or return the first 50:

$new_array = array_slice($array, 0, 50);

How easier do you expect it to be? ;)

like image 35
Matthew Avatar answered Oct 13 '22 11:10

Matthew