note 99184 deleted from function.usort by cmb

From: Date: Sun, 13 Oct 2019 08:14:52 +0000
Subject: note 99184 deleted from function.usort by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212631@lists.php.net to get a copy of this message
Note Submitter: phil at lavin dot me dot uk ---- 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); ?>

« previous php.notes (#212631) next »