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
WBOYOriginal
2016-08-08 09:21:312330browse

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

);

If you want to get 21, then you have to

$maxKey = 0;

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

    if( $k > $maxKey ) {

        $maxKey = $k;

    }

}

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

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

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

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.

Statement:
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