Search code examples
phparrayssortingmultidimensional-arraycustom-sort

Move an array with a qualifying value to the end of the array


I have an array of objects and want to move one of the objects to the last position in the array. The object to be moved can be identified by its property value -- R in this example. The first level index of the qualifying object is not known in advance. I am seeking a stable sort so that other values simply "slide forward" after the movable object is positioned at the end.

[
    (object) ['pagerank' => 3],
    (object) ['pagerank' => 1],
    (object) ['pagerank' => 'R'],
    (object) ['pagerank' => 2],
    (object) ['pagerank' => 7]
]

Desired result:

[
    (object) ['pagerank' => 3],
    (object) ['pagerank' => 1],
    (object) ['pagerank' => 2],
    (object) ['pagerank' => 7]
    (object) ['pagerank' => 'R'],
]

Solution

  • If the index is unknown:

    foreach($array as $key => $val) {
        if($val->pagerank == 'R') {
            $item = $array[$key];
            unset($array[$key]);
            array_push($array, $item); 
            break;
        }
    }
    

    If you don't want to modify the array while it is being iterated over just find the index then make the modifications.

    $foundIndex = false;
    foreach($array as $key => $val) {
        if($val->pagerank == 'R') {
            $foundIndex = $key;
            break;
        }
    }
    if($foundIndex !== false) {
        $item = $array[$foundIndex];
        unset($array[$foundIndex]);
        array_push($array, $item);
    }