note 41646 added to function.array-reverse

From: Date: Sun, 18 Apr 2004 02:06:44 +0000
Subject: note 41646 added to function.array-reverse
Groups: php.notes 
Request: Send a blank email to php-notes+get-68274@lists.php.net to get a copy of this message
In answer to Ashkay's question, the function to reverse an array in place (ie not returning a value, but reordering the given array, would depend on whether you wanted to preserve the keys. If you don't care about the keys, it can be done very simply: function array_reverse_2( &$a, $n ) { $b = Array(); for( $i = 0; $i < $n; $i++ ) $b[] = array_pop( $a ); $a = $b; } In fact you don't even need to supply the number of items in the array as in your question, because it is not needed, as in this example: function array_reverse_3( &$a ) { $b = Array(); foreach( $a as $value ) array_unshift( $b , $value ); $a = $b; } The important thing to note in both of these examples is that what makes them work is the & symbol in the parameter list. This means, any changes made to $a actually affect the real variable passed in. In both the above examples, the keys are destroyed, so if your array is indexed by strings, those strins will be gone. If you want to preservet the keys it gets a little trickier... function array_reverse_4( &$a ) { $keys = Array(); $values = Array(); foreach( $a as $key => $value ) { array_unshift( $keys , $key ); array_unshift( $values , $value ); } $a = Array(); foreach( $keys as $index => $key ) { $a[$key] = $values[$index]; } } ---- Manual Page -- http://www.php.net/manual/en/function.array-reverse.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+41646 Delete -- http://master.php.net/manage/user-notes.php?action=delete+41646&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+41646&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#68274) next »