PHP Conference Kansai 2025

uasort

(PHP 4, PHP 5, PHP 7, PHP 8)

uasortOrdena un array utilizando una función de retrollamada

Descripción

uasort(array &$array, callable $callback): true

Ordena array en el lugar de tal manera que la correlación entre las claves y los valores sea conservada, utilizando una función de comparación definida por el usuario.

Utilizado habitualmente al ordenar arrays asociativos donde el orden actual de los elementos es significativo.

Nota:

Si dos miembros se comparan como iguales, ellos mantendrán su orden original. Antes de PHP 8.0.0, su orden relativo en un array ordenado era indefinido.

Nota:

Reinicia el puntero interno del array al primer elemento.

Parámetros

array

El array de entrada.

callback

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback(mixed $a, mixed $b): int
Precaución

Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valores devueltos

Siempre devuelve true.

Historial de cambios

Versión Descripción
8.2.0 The return type is true now; previously, it was bool.
8.0.0 Si callback espera que se pase un parámetro por referencia, esta función ahora emitirá un E_WARNING.

Ejemplos

Ejemplo #1 Ejemplo con uasort()

<?php
// Función de comparación
function cmp($a, $b) {
if (
$a == $b) {
return
0;
}
return (
$a < $b) ? -1 : 1;
}

// Array a ordenar
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);

// Ordena y muestra el array resultante
uasort($array, 'cmp');
print_r($array);
?>

El resultado del ejemplo sería:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

Ver también

add a note

User Contributed Notes 4 notes

up
152
magikMaker
14 years ago
a quick reminder on the syntax if you want to use uasort in a Class or Object:

<?php

// procedural:
uasort($collection, 'my_sort_function');

// Object Oriented
uasort($collection, array($this, 'mySortMethod'));

// Objet Oriented with static method
uasort($collection, array('self', 'myStaticSortMethod'));

?>
up
34
yannick dot battail at gmail dot com
14 years ago
An Example using anonymous function.
Anonymous functions make some time the code easier to understand.
<?php
$fruits
= array('Orange9','Orange11','Orange10','Orange6','Orange15');
uasort ( $fruits , function ($a, $b) {
return
strnatcmp($a,$b); // or other function/code
}
);
print_r($fruits);
?>
returns
Array
(
[3] => Orange6
[0] => Orange9
[2] => Orange10
[1] => Orange11
[4] => Orange15
)
up
5
php at eden2 dot com
21 years ago
Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()?

After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this:

"john" => "$23.12"
"tim" => "$6.50"
"bob" => "$18.54"

and getting back:

"tim" => "$6.50"
"bob" => "$18.54"
"john" => $23.12"

(assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)
up
1
raveren at gmail dot com
4 months ago
Since php7.0 you can replace this boilerplate

if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;

with the spaceship operator:
https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.spaceship-op

return $a <=> $b;
To Top