In PHP, array_reverse() or array_flip() function can be used to achieve array reversal. array_reverse() can reverse the array elements. It will reverse the order of the elements in the original array, create a new array and return it. The syntax is "array_reverse(array,preserve)". array_flip() can reverse the array key-value pairs and exchange the positions of keys and values in the array. The syntax is "array_flip(array)".
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
Array inversion can be divided into:
Reverse the position of array elements
Reverse the position of keys and values
In php, array_reverse is available () or array_flip() function to achieve.
Method 1: Use array_reverse() to reverse the position of array elements
array_reverse() function returns an array in the reverse order of elements; It flips the order of elements in the original array, creates a new array and returns it.
Grammar format:
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. Possible values:
|
<?php header("Content-type:text/html;charset=utf-8"); $array= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); var_dump(array_reverse($array)); var_dump(array_reverse($array,true)); ?>
<?php header('content-type:text/html;charset=utf-8'); $arr =array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota"); echo "原数组顺序:"; var_dump($arr); echo "<br>数组反转后的顺序:"; var_dump(array_reverse($arr)); var_dump(array_reverse($arr,true)); ?>
Method 2: Use array_flip() to reverse the positions of keys and values
array_flip() function can exchange the keys and values in the array<?php header("Content-type:text/html;charset=utf-8"); $arr1=array("aaa"=>11,"bbb"=>22,"ccc"=>33); echo "原数组:"; var_dump($arr1); $arr2=array_flip($arr1); echo "反转数组键值对的数组:"; var_dump($arr2); ?>
PHP Video Tutorial"
The above is the detailed content of How to reverse an array in php. For more information, please follow other related articles on the PHP Chinese website!