PHP – Array Functions

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

	$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 
    [12] => 123
    [45] => 456
    [78] => 789
    [ab] => abc
    [lm] => lmn
    [xy] => xyz

By Vaseem Ansari

I’m Vaseem, a Software Engineer by Profession, a Traveler, a Foodie by Heart and the founder of 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 comment

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