User Contributed Notes 15 notes

It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:

this is a function to move items in an array up or down in the array. it is done by breaking the array into two separate arrays and then have a loop creates the final array adding the item we want to move when the counter is equal to the new position we established the array key, position and direction were passed via a query string

<?php
//parameters
//$array- the array you are modifying
//$keytomove - the key of the item you wish to move
//$pos - the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir - the direction you want to move it - "up"/"dn"

function change_pos($array, $keytomove, $pos, $dir){
//count the original number of rows
$count = count($array);
//set the integer we will use to place the moved item
if($dir=="up"){
if($pos==1){
//if the item is already first and we try moving it up
//we send it to the end of the array
$change = $count;
}else{
//anywhere else it just moves back one closer to the start of the array
$change = $pos-1;
}
}
//do the same for the down button
if($dir=="dn"){
if($pos==$count){
$change = 1;
}else{
$change = $pos+1;
}
}
//copy the element that you wish to move
$move = $array[$keytomove];
//delete the original from the main array
unset($array[$keytomove]);
//create an array of the names of the values we
//are not moving
$preint = 1;
foreach($array as $c){
$notmoved["{$preint}"] = $c['name'];
$preint++;
}
//loop through all the elements
$int = 1;
while($int<=$count){
//dynamically change the key of the unmoved item as we increment the counter
$notmovedkey = $notmoved["$int"];
//when the counter is equal to the position we want
//to place the moved entry we pump it into a new array
if($int==$change){
$neworder["{$keytomove}"] = $move;
}
//add all the other array items if the position number is not met and
//resume adding them once the moved item is written
if($contkey!=""){
$neworder["{$notmovedkey}"] = $array["{$notmovedkey}"];
}
$int++;
}

When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won't return the correct key value; you must first position at end() of the array: