Categories
PHP

PHP – Array Functions

Sort a numeric array having custom index values.

Sort a numeric array having custom index values.
Suppose you are having a array like below.

<?php
	$array['ab']	=	'abc';
	$array['xy']	=	'xyz';
	$array['lm']	=	'lmn';
	
	$array['45']	=	'456';
	$array['78']	=	'789';
	$array['12']	=	'123';

//	Then you can use below solution to sort above array.

	echo '<pre>';print_r($array);
	//preserve arrays keys for later use
	$ar1	= array_keys($array);
	
	//preserve array's values for later use
	$ar2	= array_values($array);
	
	//perform sorting by value and then by key
	array_multisort($ar2, SORT_ASC, $ar1, SORT_ASC);
	
	//combine sorted values and keys arrays to new array
	$sorted_array = array_combine($ar1, $ar2);
	
	echo '<pre>';print_r($sorted_array);
?>

Output will be 
Array
(
    [12] => 123
    [45] => 456
    [78] => 789
    [ab] => abc
    [lm] => lmn
    [xy] => xyz
)

Stay in touch

For a daily email update, click HERE or enter your email and stay on top of things by receiving weekly news in your inbox.

By Vaseem Ansari

I’m Vaseem, a Software Engineer by Profession, a Traveler, a Foodie by Heart and the founder of VaseemAnsari.com. I started traveling from college days and it has become a part of me now. So when ever I happen to get a chance I pack my bag and am on the roads. You can follow me on these social networks Facebook, Twitter, Google+ and Linkedin.

Leave a Reply

Your email address will not be published. Required fields are marked *