PHP Function to get First 5 Values of array

独自空忆成欢 提交于 2019-12-04 16:12:00

问题


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?


回答1:


Use array_slice() function:

$newArray = array_slice($originalArray, 0, 5, true);



回答2:


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



来源:https://stackoverflow.com/questions/4563958/php-function-to-get-first-5-values-of-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!