PHP – Array Functions

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.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>