Logo

Programming-Idioms

History of Idiom 28 > diff from v49 to v50

Edit summary for version 50 by ancarda:
[PHP] Format code snippet to PSR-12, use single quotes for higher performance

Version 49

2019-09-26, 19:04:40

Version 50

2019-09-27, 09:52:33

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.
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