phparrayssortingcustom-sort

Move a specified value to the last position in an array without changing the position of keys


I need to shift an array with ID's so the ID(person) can't get his own ID unless the "game" is over.

So I got this:

$array = array(
    "2" => "2",
    "3" => "3",
    "6" => "6",
    "8" => "8",
    "12" => "12",
);

And I want it this way:

$array = array(
    "2" => "3",
    "3" => "6",
    "6" => "8",
    "8" => "12",
    "12" => "2",
);

Solution

  • So after long trying and getting some help from an old friend this is the final result:

        $prev = null;
        $firstIndex = null;
        foreach ($userArr as $i => $user) {
            if (is_null($prev)) {
                $firstIndex = $i;
                $prev = $user;
                continue;
            }
            $userArr[$i] = $prev;
            $prev = $user;
        }
        $userArr[$firstIndex] = $prev;