I have a PHP array similar to this:
0 => \"red\",
1 => \"green\",
2 => \"blue\",
3 => \"yellow\"
I want to move yellow to index
EDITED
This is an update based on the question and liking the generic aspects of the answer by Peter Bailey. However, the code is too function/memory intensive for me so below just does a simple swap of the $from and $to values. This method does not cause the array in question to be resized at all, it simply swaps to values within it.
Second Edit: I added in some more argument checking as mentioned in the comments.
function moveValueByIndex( array $array, $from=null, $to=null )
{
// There is no array, or there are either none or a single entry
if ( null === $array || count($array) < 2 )
{
// Nothing to do, just return what we had
return $array;
}
if ( null === $from )
{
$from = count( $array ) - 1;
}
if ( null === $to )
{
$to = 0;
}
if ( $to == $from )
{
return $array;
}
if ( !array_key_exists($from, $array) )
{
throw new Exception( "Key $from does not exist in supplied array." );
}
$value = $array[$from];
$array[$from] = $array[$to];
$array[$to] = $value;
return $array;
}
Forgive me if I should have just added this in a comment to Peter's post.. it just was too long to inline all of this there :/