Home > Backend Development > PHP Tutorial > Get the key value of the last element of the array

Get the key value of the last element of the array

WBOY
Release: 2016-08-08 09:21:31
Original
2329 people have browsed it

Today, in a scenario, you need to get the maximum key value of an array,

For example:

$arr = array(

    11 => 1,

     6  => 2,

     9  => 5,

     21 => 1

);
Copy after login

If you want to get 21, then you have to

$maxKey = 0;

foreach( $arr as $k => $v ) {

    if( $k > $maxKey ) {

        $maxKey = $k;

    }

}
Copy after login

I thought this was more troublesome, but later I checked the information and found that this is also possible. ,

ksort( $arr );

end( $arr );

echo key( $arr );
Copy after login

That is, after k sorting, use end to point the pointer to the last element of the array, and then output the key of the array.

There is also this way, reverse the array, and then get the maximum value, but this will change the array

echo max( array_flip($arr) );
Copy after login

Of course, there is also this way, first get all the keys, and then get the largest key
$keys = array_keys($arr);

echo max($keys);
Copy after login

As for which one is better. . . It has not been tested yet

Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces how to get the key value of the last element of the array, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template