Programming-Idioms

History of Idiom 28 > diff from v35 to v36

Edit summary for version 36 :
[PHP] Less code

Version 35

2016-12-11, 21:15:01

Version 36

2016-12-18, 02:55:34

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 the 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 the type Item of the objects in items.

Code
class Item
{
    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;
}

$items[] = new Item(5.0);
$items[] = new Item(3.0);
$items[] = new Item(-1.0);
$items[] = new Item(2.5);

usort($items, "cmp"); // sort itemsay of Items using `cmp` function

foreach ($items as $x) {
    echo "{$x->p}\n";
}
Code
function cmp($a, $b)
{
    if ($a->p == $b->p)
        return 0;
    return ($a->p < $b->p) ? -1 : 1;
}

usort($items, "cmp");
Comments bubble
Classic use of usort with a custom function for sorting objects by property.
Comments bubble
Use of usort with a custom function cmp for sorting objects by property.
Doc URL
http://php.net/manual/en/function.usort.php
Doc URL
http://php.net/manual/en/function.usort.php
Demo URL
http://codepad.org/OsWlhVpV
Demo URL
http://codepad.org/OsWlhVpV