I have a PHP array similar to this:
0 => \"red\",
1 => \"green\",
2 => \"blue\",
3 => \"yellow\"
I want to move yellow to index
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 )
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);
}
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. :)
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"
}
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;
}
$array = array(
'red',
'green',
'blue',
'yellow',
);
$last = array_pop($array);
array_unshift($array, $last);