Without creating a new array:
$order_arr = [3, 1, 2, 0]; $array = [11,22,33,44]; $temp = []; foreach ($order_arr as $key => $value) { // Используйте это условие если ожидается, что элементов на своих местах // больше, чем элементов, которые надо поменять местами // if (($key != $value) && !isset($temp[$value])) { if (!isset($temp[$value])) { // PHP 7.1++ // [$array[$key], $array[$value]] = [$array[$value], $array[$key]]; // $temp[$key] = TRUE; // PHP 7.1-- list($array[$key],$array[$value]) = array($array[$value],$array[$key]); $temp[$key] = TRUE; } } var_dump($array);
A small review:
1) The method I proposed: the fastest and requires an average amount of memory;
2) The method proposed by Kirill Korushkin : a little longer and a little more memory will be executed (by creating a new array);
3) The method proposed by Alex : will be the longest, but the least take the memory.
PS If the volumes of the arrays are not large - take any method that you visually like, if the arrays are large, then you should think about optimization, choose what is closer to you.
qwerty-0
should beqwerty-1
- Alex