0

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 ))

Humayun Shabbir
  • 2,961
  • 4
  • 20
  • 33
Cab
  • 121
  • 1
  • 1
  • 12

3 Answers3

6

Number of elements: count()

$n = count($array);

First 5 elements: array_slice()

$new_array = array_slice($array, 0, 5);
mcont
  • 1,749
  • 1
  • 22
  • 33
  • Of course, `array_slice` doesn't care if the array is smaller than five, it just returns the slice *up to five*. The question isn't clear what behavior OP wants when the array is smaller than five. – kojiro Aug 02 '14 at 13:04
  • I think the whole array – mcont Aug 02 '14 at 13:09
4

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);
}
Charlotte Dunois
  • 4,638
  • 2
  • 20
  • 39
  • Thanks, the `array_slice` returns the first values if the array is not sorted ? – Cab Aug 02 '14 at 12:46
  • 1
    It returns the elements based on offset and length (2nd and 3rd parameter). So it starts at the offset 0 (beginning) and returns 5 elements. – Charlotte Dunois Aug 02 '14 at 12:47
3

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

Community
  • 1
  • 1
xitas
  • 1,136
  • 3
  • 23
  • 47
  • 3
    You do know what array_shift() does? It makes absolutely no sense to use it here. – Charlotte Dunois Aug 02 '14 at 12:55
  • array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. this will solve number difference. – xitas Aug 02 '14 at 12:59
  • 1
    No it won't. Since you're using it wrong and he wants the first 5 elements and not the five last elements. And you'd even have to make a loop to make it dynamic. – Charlotte Dunois Aug 02 '14 at 13:01
  • Oh sorry I was look somewhere else! I have edited my answer. thanks @CharlotteDunois – xitas Aug 02 '14 at 13:04