Logo

Programming-Idioms

History of Idiom 28 > diff from v50 to v51

Edit summary for version 51 by ancarda:
[PHP] Fix explanation box (bad underscore)

Version 50

2019-09-27, 09:52:33

Version 51

2019-09-27, 09:52:52

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
function cmp($a, $b)
{
    if ($a->p == $b->p) {
        return 0;
    }

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

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

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

usort($items, 'cmp');
Comments bubble
Use of usort with a custom function cmp for sorting objects by property.

Use triple equals ($a->p _=== $b->p) for higher performance if you know the types will be identical.
Comments bubble
Use of usort with a custom function cmp for sorting objects by property.

Use triple equals ($a->p === $b->p) for higher performance if you know the types will be identical.
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