Yassine Yassine - 8 days ago 5
PHP Question

Edit array placement

I am having a simple issue with ordering an array elements.
Let's assume we have an array like this

[0]=>zero
[1]=>one
[2]=>two
[3]=>three


What i want is a way to move some elements to first position for example move one and two to first positions so i will have:

[1]=>one
[2]=>two
[0]=>zero
[3]=>three


and this should be done without knowing the current position of the element in the array which means it should be done by specifying the name of wanted element to move.
I thought about array_splice() but it won't work since i should specify the key of the element in array.

Answer

You could build two arrays (one with the searched values and one without) and merge them. Keep in mind that if you want to keep numeric keys, you should use the + operator instead of array_merge :

<?php

$array = array('zero', 'one', 'two', 'three');
$searched_values = array('one', 'two');
$array_first = $array_second = array();

foreach ($array as $key=>$value) {
    if (in_array($value, $searched_values))
        $array_first[$key] = $value;
    else
        $array_second[$key] = $value;
}

$array_end = $array_first + $array_second;

echo '<pre>'; print_r($array_end); echo '</pre>';

Returns :

Array
(
    [1] => one
    [2] => two
    [0] => zero
    [3] => three
)

EDIT : Keeping the $searched_values order

In this case, you just need to loop over the serached values in order to build an array of found values and simultaneously delete the initial array's entry :

<?php
    $array = array('zero', 'one', 'two', 'three'); 
    $searched_values = array('one', 'three', 'two');
    $array_found = array();
    foreach ($searched_values as $key=>$value) {
        $found_key = array_search($value, $array);
        if ($found_key !== false) {
            $array_found[$found_key] = $value;
            unset($array[$found_key]);
        }
    }
    $array_end = $array_found + $array;
    echo '<pre>'; print_r($array_end); echo '</pre>';
?>

Returns :

Array
(
    [1] => one
    [3] => three
    [2] => two
    [0] => zero
)