note 33706 added to function.array-reverse
| From: | zee4speed at rack1 dot php dot net | Date: | Fri, 04 Jul 2003 15:26:27 +0000 |
| Subject: | note 33706 added to function.array-reverse | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-51516@lists.php.net to get a copy of this message | ||
(ANOTHER WAY TO DO) m dot weber at luna-park dot de
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;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.array-reverse.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33706
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33706&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33706&report=yes