Page 1 of 1

usort and strlen function problem

Posted: Mon Aug 22, 2011 12:03 pm
by musicmancanora4
Hi i am trying to understand what this code is doing and struggling to understand how it works.
If someone

The parts im unsure of are listed below
-------- return ($1_a < $1_b) ? -1 : 1;

also not sure why its needs => in the array

lastly not sure why it needs a while loop

if someone could give me an clear explanation that would be great so i understand it.

cheers


Code: Select all

<?php 

function by_length($a, $b)
{
    
    $1_a = strlen($a);
    $1_b = strlen($b);
    
   
    if ($1_a = = $1_b) {
        return 0;
    }
    return ($1_a < $1_b) ? -1 : 1;
}

$countries = array("e" => "united states"
				   "d" => "united kindom"
				   "c" => "canada"
				   "b" => "costa rica"
				   "a" => "germany");

usort($countries, by_length);

while (list($key,$val)) = each ($countries))
{


 echo "element $key equals $val <BR>\n";
}


?>

Re: usort and strlen function problem

Posted: Mon Aug 22, 2011 12:35 pm
by Celauran
musicmancanora4 wrote:return ($1_a < $1_b) ? -1 : 1;
This is a ternary operator. It is essentially the same as:

Code: Select all

if ($1_a < $1_b)
{
    return -1;
}
else
{
    return 1;
}
musicmancanora4 wrote:also not sure why its needs => in the array
This is used to name the indices so that you can use $arrayname['foo'] rather than $arrayname[0].

Re: usort and strlen function problem

Posted: Mon Aug 22, 2011 12:36 pm
by AbraCadaver
Well those are not valid variable names. Variables can't start with a number. Maybe you want to use a lowercase L? But in premise: if $1_a < $1_b then return -1 otherwise return 1. This is what usort() uses to determine which of the two args should be sorted above the other.

=> is used to specify key and value in an array. Look up arrays in the manual.

The loop is looping through the array to display each entry. How else would you do it?

Also, you need to quote the function name in the usort() arg.