Last active
August 29, 2015 14:07
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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