Oihana PHP

sortBy.php

Table of Contents

Functions

sortBy()  : array<int|string, mixed>
Returns a copy of an array sorted by a computed value.

Functions

sortBy()

Returns a copy of an array sorted by a computed value.

sortBy(array<int|string, mixed> $items, callable $selector[, bool $desc = false ]) : array<int|string, mixed>

The $selector callback is invoked once per entry as fn( $value , $key ) and its result is used as the sort weight (compared with the spaceship operator <=>). The sort is stable (PHP ≥ 8.0): entries with equal weights keep their original relative order. Original keys are preserved.

Parameters
$items : array<int|string, mixed>

The array to sort.

$selector : callable

The weight callback: fn( $value , $key ): mixed.

$desc : bool = false

Whether to sort in descending order. Default false.

Tags
example
use function oihana\core\arrays\sortBy;

$people =
[
    [ 'name' => 'Alice' , 'age' => 30 ] ,
    [ 'name' => 'Bob'   , 'age' => 25 ] ,
    [ 'name' => 'Carol' , 'age' => 35 ] ,
];

$byAge = sortBy( $people , fn( $p ) => $p[ 'age' ] ) ;
// Bob (25) , Alice (30) , Carol (35)

$byAgeDesc = sortBy( $people , fn( $p ) => $p[ 'age' ] , true ) ;
// Carol (35) , Alice (30) , Bob (25)
author

Marc Alcaraz (ekameleon)

since
1.0.9
Return values
array<int|string, mixed>

A new array sorted by the computed weights, keys preserved.

On this page

Search results