Open In App

PHP | ArrayIterator uasort() Function

Last Updated : 21 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads