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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to reorder an array according to given indexes in PHP

1 Answer

0 votes
function print_arr($arr) {
    $size = count($arr);
    
	for ($i = 0; $i < $size; $i++) {
		echo $arr[$i] . " ";
	}
	echo "\n";
}

function reorder(&$arr, & $indexes, $i) {
    $size = count($arr);
	if ($i < $size) {
		$data = $arr[$i];
		
		reorder($arr, $indexes, $i + 1);
			
		$arr[$indexes[$i]] = $data;
	}
}


$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$indexes = array(1, 0, 4, 3, 2, 5, 9, 7, 8, 6);

print_arr($arr);
print_arr($indexes);

reorder($arr, $indexes, 0);

print_arr($arr);




/*
run:
     
1 2 3 4 5 6 7 8 9 10 
1 0 4 3 2 5 9 7 8 6 
2 1 5 4 3 6 10 8 9 7 
     
*/

 



answered Nov 28, 2021 by avibootz

Related questions

1 answer 335 views
1 answer 249 views
1 answer 272 views
1 answer 265 views
1 answer 319 views
1 answer 263 views
1 answer 271 views
...