Programming-Idioms

History of Idiom 28 > diff from v27 to v28

Edit summary for version 28 :
New PHP implementation by user [nvius]

Version 27

Version 28

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of type Item of the objects in items.

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of type Item of the objects in items.

Code
class Test
{
    public $p;

    public function __construct($p)
    {
        $this->p = $p;
    }
}

function cmp($a, $b)
{
    if ($a->p == $b->p) {
        return 0;
    }

    return ($a->p < $b->p) ? -1 : 1;
}

$arr[] = new Test(5.0);
$arr[] = new Test(3.0);
$arr[] = new Test(-1.0);
$arr[] = new Test(2.5);

usort($arr, "cmp");

foreach ($arr as $x) {
    echo "{$x->p}\n";
}
Comments bubble
Classic use of usort with a custom function for sorting objects by property.
Doc URL
http://php.net/manual/en/function.usort.php
Demo URL
http://codepad.org/dvWYDw9x