$array = array( 'A','B','C', 'D','E','F', 'G','H','I','J' ); $new = array(); if(count($array) % 2 != 0) { array_pop($array); // Got to remove 1 element to make them even. } foreach($array as $item) { $_t = array_pop($array); //Key if(!isset($new[$item])) { $new[$item] = $_t; $new[$_t] = $item; } } var_dump($new);
This will print:
array(10){ ["A"]=> string(1) "J" ["J"]=> string(1) "A" ["B"]=> string(1) "I" ["I"]=> string(1) "B" ["C"]=> string(1) "H" ["H"]=> string(1) "C" ["D"]=> string(1) "G" ["G"]=> string(1) "D" ["E"]=> string(1) "F" ["F"]=> string(1) "E" }
how it works, it cyclically changes the values ββand at the same time deletes the value, so you always have 2 values ββat the same time, but at the same time it reduces the array by 1.
then when we install new keys, they install both of them into a new array, so the next time the loop repeats, if the same value is returned, it is simply discarded :)
RobertPitt
source share