Home >Backend Development >PHP Tutorial >Get the key value of the last element of the array
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 );
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) );
$keys = array_keys($arr); echo max($keys);
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.