anything wrong with this code?

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
qingren
Forum Newbie
Posts: 3
Joined: Thu Oct 23, 2003 3:04 am

anything wrong with this code?

Post by qingren »

Code: Select all

<?php
function by_length ($a ,$b ){
$l_a=strlen($a);
$l_b=strlen($b);
if ($l_a==$l_b) return 0;

return ($l_a<$l_b)?-1:1;
}

$countries=array("e"=>"United States",
		     "d"=>"United Kingdom",
		     "c"=>"Canada",
		     "b"=>"Costa Rica",
		     "a"=>"Germany");
usort ($countries, by_length);
while (list ($key,$val)=each($countries)){
echo "Element $key equals $val<br>\n";
}

Newbie here
thanks in advance.
?>
Last edited by qingren on Thu Oct 23, 2003 3:13 am, edited 1 time in total.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

What do you mean?

Do you get an error?

Mark
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

?

Post by itsmani1 »

wel i donot think so identify if any
qingren
Forum Newbie
Posts: 3
Joined: Thu Oct 23, 2003 3:04 am

Post by qingren »

Sorry.
At first i get the error msg below.

Notice: Use of undefined constant by_length - assumed 'by_length' in E:\Program Files\Apache Group\Apache2\htdocs\myroot\mypractice\usort.php on line 16

But when i change the code from

usort ($countries, by_length);

to

usort ($countries, "by_length");

it is running fine.....
is it right to code so? ;)
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

is it right to code so?
Yes. usort ($countries, by_length); will look for a constant named by_length, for example, define('by_length', 'hellooooo');

But you want by_length to refer to the the function named 'by_length' so you must do usort ($countries, 'by_length');
Last edited by markl999 on Thu Oct 23, 2003 3:45 am, edited 1 time in total.
qingren
Forum Newbie
Posts: 3
Joined: Thu Oct 23, 2003 3:04 am

Post by qingren »

Thank you very much..;)
Post Reply