PHP | ArrayIterator uasort() Function

The ArrayIterator::uasort() function is an inbuilt function in PHP which is used to sort the element using a user-defined comparison function and maintain their index association.

Syntax:

void ArrayIterator::uasort( callable $cmp_function )

Parameters: This function accepts a single parameter $cmp_function which is the user-defined comparison function. This comparison function accepts two parameters which are the values of the ArrayIterator and returns less than, equals to or greater than zero if the first argument is less than, equals to or greater than zero respectively.

Return Value: This function does not return any value.

Below programs illustrate the ArrayIterator::uasort() function in PHP:
strong>Program 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declare an ArrayIterator
$arrItr = new ArrayIterator(
    array(
        "a" => 4,
        "b" => 2,
        "g" => 8,
        "d" => 6,
        "e" => 1,
        "f" => 9
    )
);
  
// User defined comparator function 
function sorting($a, $b) { 
    if($a == $b)
        return 0; 
    return ($a < $b) ? -1 : 1; 
  
$arrItr->uasort("sorting"); 
    
// Printing the sorted array. 
print_r($arrItr); 
  
?>

chevron_right


Output:

ArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [e] => 1
            [b] => 2
            [a] => 4
            [d] => 6
            [g] => 8
            [f] => 9
        )

)

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
     
// Declare an ArrayIterator
$arrItr = new ArrayIterator(
    array(
        "a" => "Geeks",
        "b" => "for",
        "c" => "Geeks",
        "d" => "Computer",
        "e" => "Science",
        "f" => "Portal"
    )
);
    
// Declare a comparison function to sort  
// values in descending order 
function comparison($val1, $val2) { 
    if ($val1 == $val2) { 
        return 0; 
    
    else if($val1 > $val2
        return -1; 
    else
        return 1; 
    
$arrItr->uasort('comparison'); 
    
// Print the sorted ArrayObject 
print_r($arrItr); 
  
?>

chevron_right


Output:

ArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [b] => for
            [e] => Science
            [f] => Portal
            [a] => Geeks
             => Geeks
            [d] => Computer
        )

)

Reference: https://www.php.net/manual/en/arrayiterator.uasort.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.