Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to rearrange an array and set arr[i] to arr[arr[index]] to index in PHP

1 Answer

0 votes
function rearrange_array(&$arr) {
    $size = count($arr);
    
    for ($i = 0; $i < $size; $i++)
        $arr[$i] += ($arr[$arr[$i]] % $size) * $size;
 
    for ($i = 0; $i < $size; $i++)
        $arr[$i] = intval($arr[$i] / $size);
}


$arr = array(3, 5, 0, 2, 1, 4);

// arr[arr[0]] = 2 -> arr[0] = 2
// arr[arr[1]] = 4 -> arr[1] = 4
// arr[arr[2]] = 3 -> arr[2] = 3
// arr[arr[3]] = 0 -> arr[3] = 0
// arr[arr[4]] = 5 -> arr[4] = 5
// arr[arr[5]] = 1 -> arr[5] = 1
 
rearrange_array($arr);
 
print_r($arr);



/*
run:

Array
(
    [0] => 2
    [1] => 4
    [2] => 3
    [3] => 0
    [4] => 5
    [5] => 1
)

*/

 



answered Aug 17, 2022 by avibootz
...