phparrayssortingusort

Move some items to the end of the array if they fulfill a specific condition


I have an array of paths that I would like to sort ...

Array
(
    /something/foo1
    /something/special/foo2
    /something/foo3
    /something/special/foo4
    /something/foo5
    /something/special/foo6
)

... so that all paths that contain /special/ end up at the end of the array like this:

Array
(
    /something/foo1
    /something/foo3
    /something/foo5
    /something/special/foo2
    /something/special/foo4
    /something/special/foo6
)

The original sort order of paths must remain the same (so 1,2,3,4,5,6 => 1,3,5,2,4,6). Is there an elegant way to do this? Can this be implemented by using the usort function?


Solution

  • you can use unset and append [], like so

    $x = array(1,2,3);
    $x[] = $x[1];
    unset($x[1]);
    print_r($x);
    
    Array
    (
        [0] => 1
        [2] => 3
        [3] => 2
    )
    

    You can thus loop over the array, test each element, and flip to the end the ones that contain the pattern.

    $len = count($a);
    for ($i=0; $i<$len; $i++) {
        if (...) {
            $a[] = $a[i];
            unset($a[i]);
        }
    }
    

    Edit: php's arrays are lists, hashes and arrays simultaneously. It is possible to move an element to the end while retaining its index! For example

    $a = array(1,2,3);
    
    $t = $a[1];
    unset($a[1]);
    $a[1] = $t;
    
    print_r($a);
    Array
    (
        [0] => 1
        [2] => 3
        [1] => 2
    )