note 99184 added to function.usort
| From: | phil at lavin dot me dot uk | Date: | Sun, 01 Aug 2010 18:06:07 +0000 |
| Subject: | note 99184 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171321@lists.php.net to get a copy of this message | ||
strcmp (or strcasecmp) can be used as a callback function for usort. It will cast your comparison
values to string. Thus, you can implement a __toString() method into your classes and use usort
without creating a callback function:
<?php
class Foo {
private $a;
private $b;
public function __construct($a, $b) {
$this->a = $a;
$this->b = $b;
}
public function __toString() {
return (string)$this->a;
}
}
$foo = array(new Foo('t', 'b'), new Foo('a', 'c'), new
Foo('g', 'd'));
print_r($foo);
usort($foo, 'strcasecmp');
print_r($foo);
?>
----
Server IP: 213.229.106.14
Probable Submitter: 80.229.71.19
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/99184
Del: integrated -- https://master.php.net/note/delete/99184/integrated
Del: useless -- https://master.php.net/note/delete/99184/useless
Del: bad code -- https://master.php.net/note/delete/99184/bad+code
Del: spam -- https://master.php.net/note/delete/99184/spam
Del: non-english -- https://master.php.net/note/delete/99184/non-english
Del: in docs -- https://master.php.net/note/delete/99184/in+docs
Del: other reasons-- https://master.php.net/note/delete/99184
Reject -- https://master.php.net/note/reject/99184
Search -- https://master.php.net/manage/user-notes.php