# Re: [PHP] uksort wisdom

```On Mon, 2002-02-04 at 20:52, Sondra Russell wrote:
> Hi Guys!
>
> I'm looking to get a *deeper understanding* of uksort.  My quandry:
>
> \$array[listing1][name] = "listing 1";
> \$array[listing1][premiere] = "";
> \$array[listing2][name] = "listing 2";
> \$array[listing2][premiere] = "";
> \$array[listing3][name] = "listing 3";
> \$array[listing3][premiere] = "yes";
>
> I'd like the result to come out as:
> \$array[listing3] //(this is the one with the premiere set to "yes")
> \$array[listing1] // (no premiere, but in order)
> \$array[listing2] // (again, no premiere, but again in order)
>
> So far, I've got:
>
> function cmp= (\$a,\$b) {
>       global \$array;
>       if (\$array [\$a][premiere] == "yes") {
>               return -1;
>       } else {
>               return (\$a < \$b) ? -1 : 1;
>       }
> }
>
> uksort(\$array_array,cmp);
>
> But that ends up, strangely with:
> \$array[listing3]
> \$array[listing2]
> \$array[listing1]
>
>
> Any wisdom?  Just would like a better idea of the inner workings of uksort.```
```
I would approach this by speaking the problem out to myself:

For every pair of items (call them \$a and \$b) I want to compare,
If \$a is the premiere, put it first;
Otherwise, if \$b is the premiere, put *it* first;
Otherwise, put whichever one has the lowest name first.

So...you end up with something like this:

function cmp(\$a, \$b) {
global \$array;

/* If \$a is the premiere, put it first. */
if (\$array[\$a]['premiere'] === 'yes') {
return -1;
} else if (\$array[\$b]['premiere'] === 'yes') {
/* Otherwise, if \$b is the premiere, put it first. */
return 1;
}
/* Otherwise, just string-compare the names. */
return strcmp(\$a, \$b);
}

However, I would *strongly* suggest quoting your array indices (and,
incidentally, the 'cmp' bit in the uksort() call--not doing so will
eventually bite you. For more information as to why using unquoted
string array indices is a Bad Thing, see:

http://www.php.net/manual/en/language.types.array.php#language.types.array.donts

One last thing--if it would make sense for you to sort on the 'name'
attribute instead of the array index, you can avoid having to mess
around with globals here, by using uasort() instead of uksort(), and
using the following comparison function:

function cmp(\$a, \$b) {
/* If \$a is the premiere, put it first. */
if (\$a['premiere'] === 'yes') {
return -1;
} else if (\$b['premiere'] === 'yes') {
/* Otherwise, if \$b is the premiere, put it first. */
return 1;
}
/* Otherwise, just string-compare the names. */
return strcmp(\$a['name'], \$b['name']);
}

...just 'cause globals usually cause heartache in the long run. If not,
no big worries. :)

Hope this helps,

Torben

> Best,
> Sondra

--
Torben Wilson <[EMAIL PROTECTED]>
http://www.thebuttlesschaps.com
http://www.hybrid17.com
http://www.inflatableeye.com
+1.604.709.0506

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

```