note 41646 deleted from function.array-reverse by sp

From: Date: Sun, 18 Apr 2004 03:36:32 +0000
Subject: note 41646 deleted from function.array-reverse by sp
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-68275@lists.php.net to get a copy of this message
Note Submitter: aj@bertenshaw.net ---- 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]; } }

« previous php.notes (#68275) next »