Friday, October 10, 2025
HomeLanguagesPHP | ArrayIterator uasort() Function

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:




<?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); 
  
?>


Output:

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

)

Program 2:




<?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); 
  
?>


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

RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6718 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7099 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS