Skip to content

Instantly share code, notes, and snippets.

@airani
Last active December 9, 2016 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airani/c3dc00cb98b4cae698ac877f55e84ae1 to your computer and use it in GitHub Desktop.
Save airani/c3dc00cb98b4cae698ac877f55e84ae1 to your computer and use it in GitHub Desktop.
Move an array item from an index to another index position
<?php
/**
* ArrayHelper
*
* @author Ali Irani <ali@irani.im>
*/
class ArrayHelper
{
/**
* Move an array item from an index to another index position
* @param array $array
* @param int $from
* @param int $to
*
* @return array
*/
public static function moveItem($array, $from, $to)
{
$item = array_splice($array, $from, 1);
array_splice($array, $to, 0, $item);
return $array;
}
}
@airani
Copy link
Author

airani commented Dec 9, 2016

Example:

<?php
$a = [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'];

$out = ArrayHelper::moveItem($a, 1, 3);

// $out: [0 => 'a', 1 => 'c', 2 => 'd', 3 => 'b']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment