Home > Article > Backend Development > How to reverse sort an array in php without retaining key names
Implementation steps: 1. Use the array_reverse() function to reverse sort the array. The syntax "array_reverse (original array)" will return a reverse array; 2. Use the array_values() function to reset the keys of the reverse array. Name, syntax "array_values (reverse array)", the returned array will use numerical keys, starting from 0 and increasing by 1.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use array_reverse() and The array_values() function sorts the array in reverse order without retaining the key names.
Implementation steps:
Step 1: Use array_reverse() function to reverse sort the array
array_reverse() function Returns an array in reverse element order.
array_reverse($array,$preserve)
Parameters | Description |
---|---|
array | Required . Specifies an array. |
preserve |
Optional. Specifies whether to retain the original array key names. If set to TRUE, numeric keys will be preserved. Non-numeric keys are not affected by this setting and will always be retained. This parameter is newly added in PHP 4.0.3. Possible values:
|
$preserve are specified as true, the numeric key name of the element will remain unchanged, otherwise the numeric key name will be lost (the index starts from 0 and increases by 1).
<?php header('content-type:text/html;charset=utf-8'); $a=array("Volvo","XC90","BMW","Toyota"); $reverse=array_reverse($a); $preserve=array_reverse($a,true); var_dump($a); var_dump($reverse); var_dump($preserve); ?>The second parameter $preserve is invalid for associative arrays and the key name cannot be reset.
<?php header('content-type:text/html;charset=utf-8'); $a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA"); $reverse=array_reverse($a); var_dump($a); var_dump($reverse); ?>So the array_values() function is needed.
Step 2: Use the array_values() function to reset the key name of the reverse array (the key name will become a numeric type, starting from 0 and increasing by 1)
The array_values() function returns an array containing all the values in the array. Tip: The returned array will use numeric keys, starting from 0 and increasing by 1.<?php header('content-type:text/html;charset=utf-8'); $a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA"); $reverse=array_reverse($a); var_dump($a); var_dump($reverse); $res=array_values($reverse); var_dump($res); ?>Recommended learning: "
PHP Video Tutorial"
The above is the detailed content of How to reverse sort an array in php without retaining key names. For more information, please follow other related articles on the PHP Chinese website!