Im currently having this disfunction in my code. After filtering out some elements in my array, I end up with the following.
$myArray =
//Note that index 0 till 3 doesn't exist in this array
[4] => 'elementAtFourthIndex'
[5] => 'elementAtFifthIndex'
[6] => 'elementAtSixthIndex'
Though I would like to obtain an array that is as follows:
$myArray =
[0] => 'elementAtZeroIndex'
[1] => 'elementAtFirstIndex'
[2] => 'elementAtSecondIndex'
Someone else on StackOverflow already provided this solution in another topic but that seems to be over the top hard, for something this easy:
/**
* 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
*
* @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;
}