Search code examples
phparraysrotationkeyshift

Rotate an associative array so that it begins with a nominated key


I was working with an array that I need to manipulate maintaining the keys. The array_shift() function, which I need to implement, unfortunately does not maintains the key of the processed element of the array. Please see the example code below:

$rotor = array ("A" => "R", "B" => "D", "C" => "O", "D" => "B");

$position = "C";

foreach ($rotor as $key => $value) {
    if ($key != $position) {
        $temp = array_shift($rotor);
        array_push($rotor, $temp);
    } else {
        break;
    }
}
var_dump($rotor);

Result

array(4) {
 ["C"]=>
 string(1) "O"
 ["D"]=>
 string(1) "B"
 [0]=>
 string(1) "R"
 [1]=>
 string(1) "D"
}

As you can see, the keys of the R and D elements aren't the original ones. What alternative solution do you recommend to extract a first element of an array keeping unchanged the key?

P.S: My goal is to extract the first element of the array (keeping the key), and if it is not equivalent to the variable $position, insert the element itself in the last position of the array always maintaining its key.


Solution

  • $rotor = array ("A" => "R", "B" => "D", "C" => "O", "D" => "B");
    $position = "C";
    
    foreach ($rotor as $key => $value) {
    if($key != $position) {
        array_shift($rotor);
        $rotor += array($key=>$value);
    } else {
        break;
    }
    }
    

    Try this - works for me.