Home > Article > Backend Development > How to reverse a two-dimensional array in php
php method to reverse a two-dimensional array: 1. Create a php sample file; 2. Define a two-dimensional array; 3. Reverse the array through the "array_reverse($a,true);" function; 4. , use "print_r" to print the reversed two-dimensional array.
The operating environment of this tutorial: windows10 system, PHP version 8.1, DELL G3 computer
php How to reverse a two-dimensional array ?
Use the array_reverse() function to achieve reversal.
array_reverse() The function returns an array in the reverse order of elements.
Description
array_reverse() function reverses the order of elements in the original array, creates a new array and returns it.
If the second parameter is specified as true, the key name of the element remains unchanged, otherwise the key name will be lost.
Syntax
array_reverse(array,preserve)
Parameters
array required. Specifies an array.
preserve
Optional. Specifies whether to retain the original array key names.
This parameter is newly added in PHP 4.0.3.
Possible values:
true
false
Return original Array, reverse array, flip array retaining the original array key name:
<?php $a=array("Volvo","XC90",array("BMW","Toyota")); $reverse=array_reverse($a); $preserve=array_reverse($a,true); print_r($a); print_r($reverse); print_r($preserve);?>
Output:
Array ( [0] => Volvo [1] => XC90 [2] => Array ( [0] => BMW [1] => Toyota ) ) Array ( [0] => Array ( [0] => BMW [1] => Toyota ) [1] => XC90 [2] => Volvo ) Array ( [2] => Array ( [0] => BMW [1] => Toyota ) [1] => XC90 [0] => Volvo )
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to reverse a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!