Reputation: 211
I have a PHP array similar to this:
0 => "red",
1 => "green",
2 => "blue",
3 => "yellow"
I want to move yellow to index 0. How do I do this?
Edit: My question is how do I move any one of these elements to the beginning? How would I move green to index 0, or blue to index 0? This question is not exclusively about moving the last element to the beginning.
Upvotes: 21
Views: 28988
Reputation: 2981
PHP: move any element to the first or any position:
$sourceArray = array(
0 => "red",
1 => "green",
2 => "blue",
3 => "yellow"
);
// set new order
$orderArray = array(
3 => '',
1 => '',
);
$result = array_replace($orderArray, $sourceArray);
print_r($result);
Upvotes: 0
Reputation: 61
In case someone still looking for an answer, here is an alternate way.
$colors = array("red","green","blue","yellow");
$color_to_move = ["yellow"];
$colors_wo_yellow = array_diff($colors, $color_to_move);// This will give an array without "yellow"
//Now add "yellow" as 1st element to $
array_unshift($colors_wo_yellow,$color_to_move[0]);
That's it. :)
Upvotes: 3
Reputation: 873
This is very similar to SharpC's answer but accounts for the fact that you may not know where the value is in the array (it's key) or if it is even set. The 'if' check will skip over it if the color isn't set or if it's already the first element in the array.
$color = 'yellow';
$color_array = array("red", "green", "blue", "yellow");
$key = array_search($color, $color_array);
if ($key > 0) {
unset($color_array[$key]);
array_unshift($color_array, $color);
}
Upvotes: 5
Reputation: 1691
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 :/
Upvotes: 2
Reputation: 67
If you aren't always planning on bringing the very last object to the beginning of the array, this would be the most simplistic way to go about it...
$array = array('red','green','blue','yellow');
unset($array[array_search($searchValue, $array)]);
array_unshift($array, $searchValue);
Upvotes: 0
Reputation: 7454
This seems like the simplest way to me. You can move any position to the beginning, not just the last (in this example it moves blue to the beginning).
$colours = array("red", "green", "blue", "yellow");
$movecolour = $colours[2];
unset($colours[2]);
array_unshift($colours, $movecolour);
Upvotes: 30
Reputation: 975
You want to move one of the elements to the beginning. Let's say
$old = array(
'key1' =>'value1',
'key2' =>'value2',
'key3' =>'value3',
'key4' =>'value4');
And you want to move key3 to the beginnig.
$new = array();
$new['key3'] = $old['key3']; // This is the first item of array $new
foreach($old as $key => $value) // This will continue adding $old values but key3
{
if($key != 'key3')$new[$key]=$value;
}
Upvotes: 5
Reputation: 105878
Probably the most straightforward way
array_unshift( $arr, array_pop( $arr ) );
Per your comment "how can I take any one subscript from the array and move it to the beginning", my answer above doesn't fully satisfy that request - it only works by moving the last element to the 0 index.
This function, however, does satisfy that request
/**
* 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;
}
And, in usage
$arr = array( 'red', 'green', 'blue', 'yellow' );
echo implode( ',', $arr ); // red,green,blue,yellow
// Move 'blue' to the beginning
$arr = moveValueByIndex( $arr, 2, 0 );
echo implode( ',', $arr ); // blue,red,green,yellow
Upvotes: 15
Reputation: 10087
This function will allow you to move an element to an arbitrary position within the array, while leaving the rest of the array untouched:
function array_reorder($array, $oldIndex, $newIndex) {
array_splice(
$array,
$newIndex,
count($array),
array_merge(
array_splice($array, $oldIndex, 1),
array_slice($array, $newIndex, count($array))
)
);
return $array;
}
Hopefully the usage is fairly obvious, so this:
$array = array('red','green','blue','yellow',);
var_dump(
array_reorder($array, 3, 0),
array_reorder($array, 0, 3),
array_reorder($array, 1, 3),
array_reorder($array, 2, 0)
);
Will output this:
array(4) {
[0]=>
string(6) "yellow"
[1]=>
string(3) "red"
[2]=>
string(5) "green"
[3]=>
string(4) "blue"
}
array(4) {
[0]=>
string(5) "green"
[1]=>
string(4) "blue"
[2]=>
string(6) "yellow"
[3]=>
string(3) "red"
}
array(4) {
[0]=>
string(3) "red"
[1]=>
string(4) "blue"
[2]=>
string(6) "yellow"
[3]=>
string(5) "green"
}
array(4) {
[0]=>
string(4) "blue"
[1]=>
string(3) "red"
[2]=>
string(5) "green"
[3]=>
string(6) "yellow"
}
Upvotes: 9
Reputation: 382686
You can do like this:
$array = array("red", "green", "blue", "yellow");
$last = array_pop($array);
array_unshift($array, $last);
print_r($array);
Result:
Array ( [0] => yellow [1] => red [2] => green [3] => blue )
Upvotes: 0
Reputation: 6896
$a = array('red','green', 'blue','yellow');
$b = array_reverse( $a );
If your question is how to make the last become the first.
Upvotes: 0
Reputation: 180004
$array = array(
'red',
'green',
'blue',
'yellow',
);
$last = array_pop($array);
array_unshift($array, $last);
Upvotes: 0