How to use usort in PHP

In this article, I will explain how the usort() function can be used in PHP.
  • 1497

usort() function in PHP

  • The usort() function is used to sort an array by it's value using a user-made comparison function.
  • The usort() function does not assigns new keys for the elements.
  • The usort() function is useful for sorting with custom algorithms.
  • The usort() function maintains the existing key index.
  • The usort() function returns TRUE on success, or FALSE on failure.

Syntax

usort(array,function)

Parameter

  • array array is required parameter. the determine array to be sort.
  • function function is required parameter. the function must return -1, 0, or 1 for this method to work correctly. It should be written to accept two parameters to compare.
    • If a = b, return 0
    • If a > b, return 1
    • If a < b, return -1

Example

The following example show to how the usort() function can be used in PHP.

<html>

<body>

<h3 style="color: green;">usort() function example in PHP</h3>

    <?php

    function my_sortdemo($a, $b)

    {

    if ($a == $b) return 0;

    return ($a > $b) ? -1 : 1;

    }

    $people_list = array("Nitin".'<br/>', "Arvind".'<br/>',"Rajesh".'<br/>',

    "Peter".'<br/>',"Manish".'<br/>', "Sachin".'<br/>');

    usort($people_list, "my_sortdemo");

    print_r ($people_list);

    ?>

</body>

</html>

 

Output

usortphp.jpg

You may also want to read these related articles here

Ask Your Question 

Got a programming related question? You may want to post your question here

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.