phparraysrotation

Rotate the last value of an array to be the first element without rotating keys


How would you go about rotating the values of an array in php? For example:

array ('bill'=>'bob','marley'=>'mary','jake'=>'jack');

so that it rotates the value and keeps the key so it'll become,

array ('bill'=>'jack','marley'=>'bob','jake'=>'mary');

Solution

  • Read the comment at every line for detail

    $a = array ('bill'=>'bob','marley'=>'mary','jake'=>'jack');
    $key = array_keys($a);// get all the keys of array
    $value = array_values($a);// get all the value of array
    $rev = array_reverse($value);// reverse your value
    $new_array = array_combine($key, $rev);// combine array wirh key and reverse value
     print_r($new_array);
    

    OUTPUT

    Array ( [bill] => jack [marley] => mary [jake] => bob )