Friday, September 5, 2025
HomeLanguagesArrayObject uasort() Function in PHP

ArrayObject uasort() Function in PHP

The uasort() function of the ArrayObject class in PHP is used to sort values of an ArrayObject according to a user defined comparison function. The function compares and arranges the values present in the ArrayObject according to the given comparison function. This method does not affects the key-value associations.

Syntax:

void uasort($comparator) 

Parameters: This function accepts a single parameter $comparator which is the user defined comparison function. This comparison function in turn accepts two arguments which are the values of the ArrayObject 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 returns any value.

Below program illustrate the above function:




<?php
// PHP program to illustrate the
// uasort() function
  
$arr = array("Welcome"=>"1", "to" => "2", "GfG" => "3");
  
// Create array object
$arrObject = new ArrayObject($arr);
  
// 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;
}
  
$arrObject->uasort('comparison');
  
// Print the sorted ArrayObject
print_r($arrObject);
  
?>


Output:

ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [GfG] => 3
            [to] => 2
            [Welcome] => 1
        )

)

Reference: http://php.net/manual/en/arrayobject.uasort.php

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6636 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS