简体   繁体   中英

PHP Array if has more than X values, return last Y values

I have very simple question about PHP. ( Please don't -1 first.)

Imagine we have this array :

Array {
[1] => Hi
[3] => Hey
[5] => You
[9] => hello
[13] => yes
[66] => Test
[86] => Test2
[96] => Test3
}

(it is not SORTed).

So , I want 2 things :

  1. First, find how many values are in this array (in this one, it is 8 );

  2. Second, IF it has more than 5 Values, Then Just return 5 First values (as i said it's not sorted in array-numbers , SO , I just want to return 5 First values )

How can we do it in PHP ?

(( I am so sorry Because i am SO beginner and can't find solution in other questions ))

Number of elements: count()

$n = count($array);

First 5 elements: array_slice()

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

To count the elements you can use count() . To get only the first five values you can use array_slice() .

if(count($array) > 5) {
    $array = array_slice($array, 0, 5);
}

You can use count to count the number of arrays.

Like this:

$result = count($array);// if array  is variable

and array_slice will be a better idea

array_slice($array, 0, 5)

for more detail see this answer:

https://stackoverflow.com/a/3771228/3151394

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM