Home >Backend Development >PHP Problem >How to reverse array in php
In PHP, array reversal can be achieved using the array_reverse() function. This function will return a new array along a given array element from end to beginning without changing the original array.
The syntax for using the array_reverse() function is as follows:
array array_reverse ( array $array , bool $preserve_keys = false )
Among them, the $array parameter is the array to be reversed, and the $preserve_keys parameter determines whether to retain the original key name of the array, and its default value is false.
The following is an example:
$fruits = array('apple', 'banana', 'orange', 'pear'); // 不保留键名 $reversed_fruits = array_reverse($fruits); print_r($reversed_fruits); // 保留键名 $reversed_fruits2 = array_reverse($fruits, true); print_r($reversed_fruits2);
The execution result is:
Array ( [0] => pear [1] => orange [2] => banana [3] => apple ) Array ( [3] => pear [2] => orange [1] => banana [0] => apple )
As can be seen from the output results, the first example does not retain the original key name, while the second This example retains the original key names.
In addition to using the array_reverse() function to reverse the array, we can also use a loop statement to achieve it. The following is a piece of code that uses a loop statement to reverse an array:
$fruits = array('apple', 'banana', 'orange', 'pear'); $reversed_fruits = array(); for ($i = count($fruits) - 1; $i >= 0; $i--) { $reversed_fruits[] = $fruits[$i]; } print_r($reversed_fruits);
The execution result is:
Array ( [0] => pear [1] => orange [2] => banana [3] => apple )
As can be seen from the output, the code also successfully reverses the array.
Whether we use the array_reverse() function or a loop statement to reverse the array, we can easily implement this operation. In actual development, we can choose the method that suits us best according to our needs.
The above is the detailed content of How to reverse array in php. For more information, please follow other related articles on the PHP Chinese website!