Gets the key value of the last element of the array

Source: Internet
Author: User
Tags php tutorial
Today a scene needs to get the maximum key value of an array,

Like what:

$arr = Array (    1,     6  = 2,     9  = 5, and     1);

If you want to get to 21, then you have to

$maxKey = 0;foreach ($arr as $k = = $v) {    if ($k > $maxKey) {        $maxKey = $k;    }}

Think this is more troublesome, later looked up the information, found that it can also,

Ksort ($arr); end ($arr); Echo key ($arr);

When k is sorted, use end to point the pointer to the last element of the array, and then output the key of the array.

Also, reverse the array and take the maximum value, but this will change the array

echo Max (Array_flip ($arr));

And, of course, get all the keys first and then get the biggest key.
$keys = Array_keys ($arr); echo Max ($keys);

As to which of the better ... Not currently tested.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The above describes the acquisition of the last element of the array key value, including the contents of the content, I hope that the PHP tutorial interested in a friend to help.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.