数组 函数
在线手册:中文 英文
PHP手册

array_reverse

(PHP 4, PHP 5)

array_reverse 返回一个单元顺序相反的数组

说明

array array_reverse ( array $array [, bool $preserve_keys ] )

array_reverse() 接受数组 array 作为输入并返回一个单元为相反顺序的新数组,如果 preserve_keysTRUE 则保留原来的键名。

Example #1 array_reverse() 例子

<?php
$input  
= array("php"4.0, array("green""red"));
$result array_reverse($input);
$result_keyed array_reverse($inputTRUE);
?>

这将使 $result$result_keyed 具有相同的单元,但是注意键名的区别。$result$result_keyed 的打印输出显示分别为:

Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

Note:

第二个参数是 PHP 4.0.3 中新加的。

参见 array_flip()


数组 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 返回一个单元顺序相反的数组

用户评论:

laymain at gmail dot com (21-Feb-2012 09:41)

<?php

function array_reverse_ref(array &$array, $preserve_keys = false)
{
   
$new_array = array();
    for (
end($array); ($key = key($array)) !== null; end($array))
    {
       
$value = array_pop($array);
        if (
$preserve_keys)    $new_array[$key] = $value;
        else               
$new_array[] = $value;
    }
   
$array = $new_array;
}

$test = array(
   
1 => 'first',
   
6 => 'mid',
   
3 => 'last',
);

array_reverse_ref($test, true);
var_dump($test);
/*
array(3) {
  [3]=>
  string(4) "last"
  [6]=>
  string(3) "mid"
  [1]=>
  string(5) "first"
}
*/

array_reverse_ref($test);
var_dump($test);
/*
array(3) {
  [0]=>
  string(5) "first"
  [1]=>
  string(3) "mid"
  [2]=>
  string(4) "last"
}
*/

Nick Kraynev (27-Jul-2011 08:15)

Another way to maintain association:

<?php
return array_compose(
   
array_reverse(array_keys($array)),
   
array_reverse(array_values($array))
);
?>

jferchaud at yahoo dot fr (17-Feb-2011 02:29)

Return an array with elements in reverse order preserving mixed type keys.

<?php
function array_reverse_order($array){
       
$array_key = array_keys($array);
       
$array_value = array_values($array);
       
       
$array_return = array();
        for(
$i=1, $size_of_array=sizeof($array_key);$i<=$size_of_array;$i++){
           
$array_return[$array_key[$size_of_array-$i]] = $array_value[$size_of_array-$i];
        }
       
        return
$array_return;
    }
?>

alfbennett at gmail dot com (06-Apr-2010 09:41)

Needed to just reverse keys. Don't flog me if there is a better way. This was a simple solution.

<?php
function array_reverse_keys($ar){
    return
array_reverse(array_reverse($ar,true),false);
}
?>

ulderico at maber dot com dot br (14-May-2009 10:33)

<?php
function array_reversed($array){
 
$array = array_reverse($array);
 
ksort($array);
  return(
$array);
}
?>

So you'll have a reversed array.. instead of an array with inverted keys.

Anonymous (01-Feb-2009 08:07)

Reversing array by reference (does not preserve keys!):

<?php
function arrayReverse(&$arr)
{
   
$c = count($arr);
    for(
$i=$c-1;$i>=0;$i--)
    {
       
$arr[$c+$i] = $arr[$i];
    }
   
$arr = array_slice($arr,$c,$c*2);
}
?>

rdx at jouwmoeder (07-Nov-2006 11:37)

As response to Ella's note:

$array[0] = 'record1';
$array[9] = 'record2';
$array[15] = 'record3';

That is ordered way easier AND faster with array_values().
array_reverse twice is unnecessary. Once array_values and all values will be saved in new keys

Ella (14-Jul-2006 01:03)

You can also use array_reverse to reset array indexes without losing the order of the values. For example when you use unset() to delete values from an array, the value gets deleted but you end up with a missing index:

$array[0] = 'record1';
$array[9] = 'record2';
$array[15] = 'record3';

Just use:

$array = array_reverse(array_reverse($array));

And your indexes get rearranged:

$array[0] = 'record1';
$array[1] = 'record2';
$array[2] = 'record3';

me2resh at gmail dot com (03-Feb-2005 09:25)

Here is my version of sorting multidimensional arrays with any key in it even if u want it alphapatically sorted by any key.

u can remove the strtolower part if you want to keep it case sensitive

function cmp($a, $b){
    return strcmp(strtolower($a["name"]), strtolower($b["name"]));
}

Michiel de Roo (08-Sep-2003 08:55)

If you need to reverse an array by reference, you can use the following function.

<?
function &array_reverse_ref(&$a) {
    $r = array();
    for($i=0, $j=count($a); $i<count($a); $i++, $j--) {
        $r[$i] =& $a[$j-1];
    }
    return $r;
}
?>

Use it like:
<?
class t {
    var $message = "message";   
}
for($i=0; $i<10; $i++) {
    $a[] = new t();
}

$ra =& array_reverse_ref($a);

$a[0]->message = "now... this works in both";
$ra[0]->message = "but.... does not work in both";

for($i=0; $i<10; $i++) {
    echo $ra[$i]->message; echo "<br>\n";
}
echo "<br>\n";
for($i=0; $i<10; $i++) {
    echo $a[$i]->message; echo "<br>\n";
}
?>

zee4speed at hotmail dot com (04-Jul-2003 06:56)

another way to ->
If you want to reverse an array with numerical indexes, you can keep them by using following code:
<?
# this is your array, and you would like to reverse it however maintain their actual index values to point to the existings.
$array_to_reverse[0]="zee";
$array_to_reverse[1]="andrew";
$array_to_reverse[2]="pablo";
$array_to_reverse[3]="mike";
$array_to_reverse[4]="ahmed";
$array_to_reverse[5]="yousra";
$array_to_reverse[6]="samir";
# you want the array to look like this so you can use a command like for each to march through the array.
$array_reversed[6]="samir";
$array_reversed[5]="yousra";
$array_reversed[4]="ahmed";
$array_reversed[3]="mike";
$array_reversed[2]="pablo";
$array_reversed[1]="andrew";
$array_reversed[0]="zee";
# however if you use array_reverse you get this:
$array_reversed[0]="samir";
$array_reversed[1]="yousra";
$array_reversed[2]="ahmed";
$array_reversed[3]="mike";
$array_reversed[4]="pablo";
$array_reversed[5]="andrew";
$array_reversed[6]="zee";
# this causes element samir to be first instead of last, just like you want.  hoever, the index value that refferences samir is now 0 instead of 6
# solution to this is the following code

$array_reversed = array_reverse ($array_to_reverse);
$size_of_array = count($array_reversed);
for ($z = 0; $z < $size_of_array; $z++){
         #do what you want
         #if you want to get the index value of the un-reveresed array, simply
         $actual_index = GetActualIndex($z,$size_of_array);
         echo $z." on array_reversed is the same ".$actual_index." on array_to_reverse<BR>\n";
}

function GetActualIndex($current_index, $size_of_array){
         $reverse_location = abs($current_index + 1 - $size_of_array);
         return $reverse_location;
}
?>

m dot weber at luna-park dot de (31-Jan-2003 03:02)

If you want to reverse an array with numerical indexes, you can keep them by using following code:

<?php
end
($gruppenarr);
do {
 
$part1=key($gruppenarr);
 
$part2=current($gruppenarr);
 
$gruppenarr2[$part1]=$part2;
} while(
prev($gruppenarr));
?>

input is $gruppenarr
output is $gruppenarr2

rahulavhad at yahoo dot com (30-Dec-2000 04:31)

This code can help in recursive reversing of the array...

<?php
$arr1
= array(2,1,array(5,2,1,array(9,8,7)),5,0);
$arr1 = array_reverse($arr1);

function
Reverse_Array($array)
{   
$index = 0;
    foreach (
$array as $subarray)
    {    if (
is_array($subarray))
        {   
$subarray = array_reverse($subarray);
           
$arr = Reverse_Array($subarray);
           
$array[$index] = $arr;
        }
        else {
$array[$index] = $subarray;}
       
$index++;
    }
    return
$array;
}

$arr2 = Reverse_Array($arr1);
?>

david at audiogalaxy dot com (04-Mar-2000 09:39)

As a further clarification: key-value pairs have an order within an array completely separate from whatever the keys happen to be - the order in which you add them.  This is the order that functions like each() and next() will move their pointer through the array.
If you add to an array without specifying the key, like $array[] = value; then an internal counter supplies the key value and then the numerical order of your keys will be identical to the the internal order.  If you "leave holes" - jumping ahead by specifying a higher number for the key, like $array[1000] = value; the internal counter gets pushed forward appropriately.  Other than its effect on this internal counter, specifying a numerical key seems no different than specifying a string.
However, some array functions, like array_merge() and array_reverse() treat keys that are numbers differently from keys that are not.

david at audiogalaxy dot com (04-Mar-2000 08:40)

With associative arrays array_reverse() keeps key => value pairs matched but reverses the order of the array as spaned by functions like each().  With numerical indexes array_reverse not only reverses position (as spaned by each) but also renumbers the keys.
Both cases seem to be what people would generally want: indeed without the renumbering behavior, someone refering to array elements by numerical key wouldn't think array_reverse did anything.
However, people who are trying to keep numerical keys associated with their values - e.g. trying to have holes in their arrays - will be foiled by the renumbering.  The most telling results come from applying array_reverse() to arrays with mixed keys (some numbers and some strings).  The strings stay attached and the rest of the keys get renumbered around them - most annoying if you are thinking what you've got is an associative array but some of your keys happen to be numbers.