Larry Ullman's Book Forums

## Recommended Posts

I've just started this book and am really confused with an expression.

Can somebody please explain the mechanism behind the expression, given below, used in Script 1.1 - sort.php

```return (\$x < \$y)
```
```// Creating an array
\$a = [1, 5];

// creating comparison function using the above expression
function comp1(\$x, \$y)
{
return (\$x < \$y);
}
// using uasort()
uasort(\$a, 'comp1');
// output the result
echo '<pre>' . print_r(\$a, 1) . '</pre>';

// creating the same function as above but interchanging the arguments position
function comp2(\$y, \$x)
{
return (\$x < \$y);
}
// using uasort()
uasort(\$a, 'comp2');
// output the result
echo '<pre>' . print_r(\$a, 1) . '</pre>';

```

This outputs

```Array
(
 => 5
 => 1
)

Array
(
 => 1
 => 5
)
```

Observation: reversing the position of arguments in function definition reverses the sort output.

```return (\$x < \$y)
```

- How and which values are returned.

##### Share on other sites

Sorry for the confusion! So the less than operator in PHP is going to return true or false, so that method therefore returns true or false: the result of the comparison. The uasort() function takes a function as its second argument. uasort() runs every item in the array through user-defined function to perform the sort. So if you had 4, 1, 5 as the array, the first comparison would be 4 and 1. comp1() would return false so uasort() would no that it should be 1 then 4. I thiiiink uasort would then run 4 and 5 through it (but I could be wrong about the sorting algorithm) and get true, meaning the order is 4 and 5, making the whole order 1, 4, 5.

Let me know if that's still not clear!

##### Share on other sites

Thanks Larry. That point is clear.

However this is not clear: Using the same array, but passing comp2() function as the second argument in uasort the result is inverted.
The difference between comp1() and comp2() function is the difference in the position of arguments.
The two function does the same comparison operation i.e \$x < \$y
Maybe am missing something about using comparison operaiton inside 'return' or the way variables behave inside a function with respect to the arguments listed while defining function?

Edited by alex_r

##### Share on other sites

Oh, sorry! The second function does the same comparison but on the opposite arguments, so instead of--for example--returning 4

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible. ×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.