In the previous article "PHP String Learning: Reverse Output All Characters", we introduced the method of reversing a string and outputting all characters in the string in reverse order. In fact, not only strings can be reversed, but arrays can also be reversed. This time we will talk about the method of reversing an array, reversing the order of the array, and outputting all elements in reverse order. You can refer to it if you need it.
When it comes to outputting array elements in reverse order, my first reaction is to use a for loop to traverse the array in reverse order. Here is the implementation method I gave:
= 0; $i--) { echo $array[$i] . "
"; } ?>
Use a for loop and set initialization Statement "$i=count($array)-1
", the value of variable$i
isarray length; set$i--
Let the value of variable $i decrement, and end the loop when $i<0. Then you can output the array in reverse order according to thearray subscript($i value). Take a look at the output:
#As you can see, all elements are printed in reverse.
But this method can only be used for index arrays whose key names are numbers. So if it is the following associative array:
$array=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");;
How to output the array elements in reverse order? You can use the array_reverse() function.
Idea:
First use the array_reverse() function to reverse the array. It will flip the order of the array elements and then return the flipped array.
Then use the foreach loop statement to traverse the reversed array and output the elements inside.
The following is the implementation method I gave:
$value){ echo "键名为:".$key.",键值为:".$value . "
"; } ?>
The output result is:
键名为:c,键值为:Toyota 键名为:b,键值为:BMW 键名为:a,键值为:Volvo
Let’s take a look at the array_reverse() function.
array_reverse( $array, $preserve )
The function returns an array with the cells in reverse order. It accepts a required parameter$array
and an omitted parameter$preserve
(default value is true).
Parameter$preserve
You can specify whether to retain the numeric key names of the original array (non-numeric keys are not affected). When the value is set to false, it means that the numeric key names are not retained.
The output result is:
Okay, that’s all. If you want to know anything else, you can click this. → →php video tutorial
Finally, I would like to recommend a free video tutorial on PHP arrays:PHP function array array function video explanation, come and learn!
The above is the detailed content of PHP array learning reverses the order and prints all elements in reverse. For more information, please follow other related articles on the PHP Chinese website!