Simple sort of two dimensional array

I’ve created an array and have assigned values read in from a file like so (only part shown here)…

$iIndex = array(array());

$iIndex[$count][0] = $lineInA;
$iIndex[$count][1] = $lineInB;


I’m visualising $iIndex having values like this…

iIndex[0][0] = “500”
iIndex[0][1] = “Smith”
iIndex[1][0] = “660”
iIndex[1][1] = “Jones”

I’d like to sort the array such that it’s in surname order like this:
660 Jones
500 Smith

I guess array_multisort() is the answer but I can’t get it to work… any help appreciated! :smiley:



If you want to use array_multisort you could use the method outlined on (, but I would personally use the code below:

[php]function sort_by_surname($a,$b) //Each parameter is an element (e.g. $a = $iIndex[0] and $b = $iIndex[1])
return strcmp($a[1],$b[1]);

$iIndex = uasort($iIndex,‘sort_by_surname’); //Just use usort() if you don’t want to maintain first level index associations.[/php]

Thanks for the reply.

I’d looked at that example on but couldn’t quite figure out how to apply it to my problem.

I sort of understand the code you provided but how/where is the comparison function actually called, or rather (as I imagine it is called by uasort() for each item in the array), how are the parameters passed?


Hi Paul,

uasort() and the other versions (usort,uksort) will automatically pass 2 parameters to whatever function you specify (you don’t need to worry about the parameters, you just need to know that your function needs to handle 2, where each parameter is an element of the array).

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

For string comparisons I tend to use the function strcmp() because it’s return value (from

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Any more questions let me know - it’s quite hard to describe though! It might be worth trying it out with a couple of different examples to try and get experience with the function(s) and see how they work first hand.

Ah, I see thank you. As you say, playing with some code will be the best route to understanding :smiley:

Well I got it to work but only if the result of the sort wasn’t assigned to the original array, like so (note slightly different variable/function naes to above):

uasort($indiIndex, ‘sortBySurname’);

and function…

function sortBySurname($a, $b){
return strcmp($a[1], $b[1]);

Is the assigment in your reply a mistake as states the return value as TRUE/FALSE to indicate succes?

Thanks again,

PS It works just as I require!

DERP! Yea, sorry, don’t know what possessed me to do that.

Glad to hear you got it sorted.

Sponsor our Newsletter | Privacy Policy | Terms of Service