PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Sat Aug 15, 2020 5:00 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 3 posts ] 
Author Message
PostPosted: Mon Aug 22, 2011 12:03 pm 
Offline
Forum Newbie

Joined: Mon Sep 21, 2009 9:17 pm
Posts: 3
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



Syntax: [ Download ] [ Hide ]
<?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";
}


?>
 


Top
 Profile  
 
PostPosted: Mon Aug 22, 2011 12:35 pm 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6425
Location: Montreal, Canada

_________________


Top
 Profile  
 
PostPosted: Mon Aug 22, 2011 12:36 pm 
Offline
DevNet Master
User avatar

Joined: Mon Feb 24, 2003 11:12 am
Posts: 2572
Location: The Republic of Texas
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.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 42 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group