Home  >  Article  >  Backend Development  >  How to reverse a two-dimensional array in php

How to reverse a two-dimensional array in php

藏色散人
藏色散人Original
2022-12-26 09:38:554783browse

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.

How to reverse a two-dimensional array in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn