note 22542 added to ref.array

From: Date: Fri, 21 Jun 2002 15:14:32 +0000
Subject: note 22542 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-32092@lists.php.net to get a copy of this message
<? $myarray = array(); $myarray[1] = 1; $myarray[2] = 2; $myarray[3] = 3; $myarray[4] = 4; // I want to move $myarray[2] to the 4th position. $ordered_array = reposition($myarray, 2,4); foreach($ordered_array as $key=>$value){ echo "ordered_array[$key] = $value"; } ?> // The output of this function will be: ordered_array[1] = 1 ordered_array[2] = 4 ordered_array[3] = 2 ordered_array[4] = 3 <? function reposition($myarray,$myarray_key,$newpos){ $oldpos = $myarray[$myarray_key]; foreach($myarray as $key=>$value){ if($key==$myarray_key){ $myarray[$key] = $newpos; }else{ if($oldpos>=$newpos){ // It's moving up the array // Values following it will go down (lower position) if($myarray[$key]<=$oldpos && $myarray[$key]>=$newpos){ $myarray[$key]++; } }else{ // It's moving down the array // Values preceding it will go up (higher position) if($myarray[$key]>=$oldpos && $myarray[$key]<=$newpos){ $myarray[$key]--; } } } } return $myarray; } ?> -- http://www.php.net/manual/en/ref.array.php http://master.php.net/manage/user-notes.php?action=edit+22542 http://master.php.net/manage/user-notes.php?action=delete+22542 http://master.php.net/manage/user-notes.php?action=reject+22542

« previous php.notes (#32092) next »