ArrayObject::uasort
Sort the entries with an user-defined comparison function and maintain key association.
<?php
void public ArrayObject::uasort ( callable $cmp_function )
where,
$cmp_function = The user defined comparison function
?>
$cmp_function
The user defined comparison function.
ATTENTION
The $cmp_function should accept two parameters which will be filled by pairs of entries.
$cmp_function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
EXERCISE
<?php
function cmp1($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$arr01 = [ 'a' => 'hello folks', 'b' => 'HELLO FOLKS',
'c' => 'Ad augusta per Angusta',
'd' => 'Is', 'e' => 'this',
'f' => 'a new example?', 'g' => -3, 'h' => -4 ];
$aarrayObject = new ArrayObject($arr01);
echo '<pre>';
print_r($aarrayObject);
echo '</pre>';
$aarrayObject->uasort('cmp1');
echo '<pre>';
print_r($aarrayObject);
echo '</pre>';
?>
RESULT
ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[a] => hello folks
[b] => HELLO FOLKS
[c] => Ad augusta per Angusta
[d] => Is
[e] => this
[f] => a new example?
[g] => -3
[h] => -4
)
)
ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[h] => -4
[g] => -3
[c] => Ad augusta per Angusta
[b] => HELLO FOLKS
[d] => Is
[f] => a new example?
[a] => hello folks
[e] => this
)
)
EXERCISE
<?php
function cmp2($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$arr02 = [6.674_083e-11, 299_792_458, 0xCAFE_F00D, 0b0101_1111 ];
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This number notations is only avalable as of PHP 7.4
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
$barrayObject = new ArrayObject($arr02);
echo '<pre>';
print_r($barrayObject);
echo '</pre>';
$barrayObject->uasort('cmp2');
echo '<pre>';
print_r($barrayObject);
echo '</pre>';
?>
RESULT
ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[0] => 6.674083E-11
[1] => 299792458
[2] => 3405705229
[3] => 95
)
)
ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[0] => 6.674083E-11
[3] => 95
[1] => 299792458
[2] => 3405705229
)
)