Skip to content

Instantly share code, notes, and snippets.

@rxnlabs
Last active August 29, 2015 14:07
Show Gist options
  • Save rxnlabs/cca2cbc17e08afa40e7f to your computer and use it in GitHub Desktop.
Save rxnlabs/cca2cbc17e08afa40e7f to your computer and use it in GitHub Desktop.
PHP - Move element to beginning of array. Shift an array's element position
<?php
/**
* Move array element by index. Only works with zero-based,
* contiguously-indexed arrays
*
* @param array $array
* @param integer $from Use NULL when you want to move the last element
* @param integer $to New index for moved element. Use NULL to push
*
* @throws Exception
*
* @link http://stackoverflow.com/questions/4126502/move-value-in-php-array-to-the-beginning-of-the-array
*
* @return array Newly re-ordered array
*/
function moveValueByIndex( array $array, $from=null, $to=null )
{
if ( null === $from )
{
$from = count( $array ) - 1;
}
if ( !isset( $array[$from] ) )
{
throw new Exception( "Offset $from does not exist" );
}
if ( array_keys( $array ) != range( 0, count( $array ) - 1 ) )
{
throw new Exception( "Invalid array keys" );
}
$value = $array[$from];
unset( $array[$from] );
if ( null === $to )
{
array_push( $array, $value );
} else {
$tail = array_splice( $array, $to );
array_push( $array, $value );
$array = array_merge( $array, $tail );
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment