Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Function to get First 5 Values of array

Tags:

arrays

php

slice

Array
(
    [university] => 57
    [iit] => 57
    [jee] => 44
    [application] => 28
    [study] => 26
    [college] => 23
    [exam] => 19
    [colleges] => 19
    [view] => 19
    [amp] => 18
)

How can I get an array with the first 5 elements?

like image 291
Mohit Avatar asked Dec 30 '10 15:12

Mohit


People also ask

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

How can we get the first element of an array in PHP?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more.

What is the use of Array_flip () function?

The array_flip() function flips/exchanges all keys with their associated values in an array.

What does Array_splice () function do give an example?

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).


2 Answers

Use array_slice() function:

$newArray = array_slice($originalArray, 0, 5, true);
like image 88
Crozin Avatar answered Oct 20 '22 05:10

Crozin


If you need the first 5 elements

  • by order of keys: use ksort(),
  • by order of values: use sort()

before the array_slice(). Insert a letter 'r' to the second place for reverse order: krsort(), arsort().

like image 4
ern0 Avatar answered Oct 20 '22 05:10

ern0