usort and strlen function problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
musicmancanora4
Forum Newbie
Posts: 3
Joined: Mon Sep 21, 2009 9:17 pm

usort and strlen function problem

Post 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";
}


?>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: usort and strlen function problem

Post 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].
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: usort and strlen function problem

Post 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.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply