Page 1 of 1

"Rearranger" class to move specified array value

Posted: Tue Aug 17, 2010 8:28 pm
by letseatfood
I just created this `Rearranger` class which will move a value at a specified index to a location between a selected index and (selected index - 1). In other words, the value is inserted between two other values.

I don't think a function that solves the same problem is in the PHP language, please correct me if I am wrong.

Anyways, I would appreciate any feedback that you can provide.

Thanks!

Code: Select all

class Rearranger
{	
	/*
	 * Determines how to move the specified value.
	 */
	public static function go($list, $indexToMove, $offset)
	{
		if(($offset == ($indexToMove - 1)) || ($offset == ($indexToMove + 1))) {
			//Value is only being moved up or down one index, so just swap the values
			$list = self::swap($list, $indexToMove, $offset);
		} else if($offset < $indexToMove) {
			//Value is being moved up (will be changing to a lower value index)
			$list = self::move($list, $indexToMove, $offset);
		} else if($offset > $indexToMove) {
			//Value will be moving down (will be changing to a higher value index)
			$list = self::move($list, $indexToMove, $offset - 1);
		} 
		return $list;
	}
	
	/* 
	 * Moves the value at $list[$indexToMove] in between
	 * $list[$offset - 1] and $list[$offset].
	 */
	public static function move($list, $indexToMove, $offset)
	{
		$container = $list[$indexToMove];
		unset($list[$indexToMove]);
		$list = array_values($list);
		$list2 = array_slice($list, $offset);
		$list = array_slice($list, 0, $offset);
		array_push($list, $container);
		return array_merge($list, $list2);
	}
	
	//Swap the values of two array indices
	public static function swap($list, $indexA, $indexB)
	{
		$vA = $list[$indexA];
		$vB = $list[$indexB];
		$list[$indexA] = $vB;
		$list[$indexB] = $vA;
		return $list;
	}
}
Here is how I use it:

Code: Select all

$a1 = array('a', 'b', 'c', 'd', 'e', 'f');

echo 'Before Rearranging:';
var_dump($a1);

echo  '4 to 1 (move up):';
$a1 = Rearranger::go($a1, 4, 1);
var_dump($a1);

echo '1 to 4 (move down):';
$a1 = Rearranger::go($a1, 1, 4);
var_dump($a1);

$a1 = Rearranger::go($a1, 2, 3);
echo '2 to 3 (swap):';
var_dump($a1);

echo '5 to 4 (swap):';
$a1 = Rearranger::go($a1, 5, 4);
var_dump($a1);

echo '3 to 3 (do nothing):';
$a1 = Rearranger::go($a1, 2, 2);
var_dump($a1);