Re: the usort 's puzzle



youngord@xxxxxxxxx wrote:
<?php
$mix=array(
array("A",10),
array("B",5),
array("C",100)
);
function com($x,$y){
echo $x[0];
}

usort($mix,'com');

?>

i think the $x[0] result is A,
but the final $x[0] result is BC.
why???

first round of usort does:

com(array("B",5),array("A",10))

which leads to that

$x=array("B",5)
$y=array("A",10)

then you echo

$x[0]

which has the value

B

the function returns nothing, which is equal to false (this moves a after b in
the mix array)

second round of usort does:

com(array("C",100),array("B",5))

which leads to that

$y=array("C",100)
$y=array("B",5)

then you echo

$x[0]

which has the value

C

the function returns nothing, which is equal to false (which moves c before b
in the mix array)


Which leads to that you geat an output of

BC

The $mix array looks now like

array(3) {
[0]=>
array(2) {
[0]=>
string(1) "C"
[1]=>
int(100)
}
[1]=>
array(2) {
[0]=>
string(1) "B"
[1]=>
int(5)
}
[2]=>
array(2) {
[0]=>
string(1) "A"
[1]=>
int(10)
}
}


I guess you really wanted

<?php
$mix=array(
array("A",10),
array("B",5),
array("C",100)
);
function com($x,$y){
return ($x[1]<$y[1])?false:true;
}

usort($mix,'com');

//To allow you to see the sorted array
var_dump($mix);
?>

Which gives you

array(3) {
[0]=>
array(2) {
[0]=>
string(1) "B"
[1]=>
int(5)
}
[1]=>
array(2) {
[0]=>
string(1) "A"
[1]=>
int(10)
}
[2]=>
array(2) {
[0]=>
string(1) "C"
[1]=>
int(100)
}
}

Kind of BAC.

--

//Aho
.



Relevant Pages

  • Re: the usort s puzzle
    ... then you echo ... second round of usort does: ... in the mix array) ...
    (alt.php)
  • Re: Dynamic Form
    ... customer will answer all 5 questions then press next. ... I have read the PHP manual pages. ... echo Age; ... only other thought is that for some reason, I can't access the array ...
    (comp.lang.php)
  • Re: Referencing Korn Shell Array Names as a Variable
    ... Your idea worked for displaying the output from the command. ... $ echo $ ... # Attempt to use variable array name and index to reference array value ... The issue is with this line of the script ...
    (comp.unix.shell)
  • Re: PHP Search & Links
    ... >> file as an array. ... >and to tell you the truth it is the first time i see something like ... I have replaced the $ at times or the echo I ... the part displaying the lines should display all lines and ...
    (alt.php)
  • Re: Best approach for server side Form Validation ?
    ... correct I need to submit to another page that uses the form data. ... in 2.php with default parameters (0 for error variable, and an array of ... for each required field use: ... for all fields use interpolated arrayvalue to, e.g., echo ...
    (comp.lang.php)