Home Backend Development PHP Tutorial How to use the usort function to custom sort an array in PHP

How to use the usort function to custom sort an array in PHP

Jun 26, 2023 pm 12:06 PM
php usort function Custom sorting

When using PHP for array operations, sorting is one of the most common operations. PHP provides many different sorting functions, including the usort function. The usort function can sort an array according to specified rules, but unlike other sorting functions, it allows users to customize the sorting rules.

This article will introduce how to use the usort function in PHP and how to use the usort function for custom sorting.

1. The basic format of the usort function

When using the usort function for sorting, we need to pay attention to the following points:

  • This function requires two parameters, The first parameter is the array that needs to be sorted, and the second parameter is a callback function used to define the sorting rules.
  • The callback function needs to define a rule for comparing the sizes of two elements. Specifically, it needs to return an integer value. The meaning of the return value is:
  • Greater than 0 means that the first element is larger than The second element is larger and needs to be swapped;
  • equals 0 means the two elements are equal and does not need to be swapped;
  • is less than 0 means the first element is smaller than the second element and does not need to be swapped. Need to exchange positions.

Speaking of which, we need to understand the anonymous functions in PHP. An anonymous function is a piece of code that does not have a name and can be defined and stored in a variable.

The following is the basic format of the usort function:

1

usort(array &$array, callable $cmp_function)

Copy after login

Among them, $array is the array that needs to be sorted, and $cmp_function is the callback function used to define the sorting rules.

2. Examples of using the usort function

Let’s take a look at examples of using the usort function.

1

2

3

4

5

6

7

8

9

10

11

12

<?php

$fruits = array("apple", "banana", "orange", "peach");

 

function cmp($a, $b)

{

    return strlen($a) - strlen($b);

}

 

usort($fruits, "cmp");

 

print_r($fruits);

?>

Copy after login

In the above example, we first defined an array $fruits, which contains four fruits. Next, we define a callback function cmp to implement the rule of sorting string lengths from small to large. In the usort function, we pass the $fruits array and the cmp function as parameters. After the function is executed, the $fruits array will be sorted according to the rules of string length from small to large.

The running results are as follows:

1

2

3

4

5

6

7

Array

(

    [0] => apple

    [1] => peach

    [2] => banana

    [3] => orange

)

Copy after login

3. Use the usort function for custom sorting

In addition to using the usort function for ordinary sorting, we can also define custom sorting according to our own needs. Define sorting rules.

The following is an example. We use the usort function to sort a two-dimensional array containing people's names and ages in ascending order of age.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?php

$people = array(

    array('name' => 'Jim', 'age' => 23),

    array('name' => 'Tom', 'age' => 18),

    array('name' => 'Lucy', 'age' => 26),

    array('name' => 'Lily', 'age' => 20),

);

 

function cmp($a, $b)

{

    return $a['age'] - $b['age'];

}

 

usort($people, "cmp");

 

print_r($people);

?>

Copy after login

In the above example, we defined a two-dimensional array $people, which contains two fields: name and age. Next, we define a callback function cmp to implement the rules of sorting by age from small to large. What is returned in the function is $a['age'] - $b['age'], which means that the array is sorted from small to large by age.

The running results are as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

Array

(

    [0] => Array

        (

            [name] => Tom

            [age] => 18

        )

 

    [1] => Array

        (

            [name] => Lily

            [age] => 20

        )

 

    [2] => Array

        (

            [name] => Jim

            [age] => 23

        )

 

    [3] => Array

        (

            [name] => Lucy

            [age] => 26

        )

 

)

Copy after login

You can see that according to the rules we defined, the $people array has been sorted from small to large by age.

Through the above example, we can find that the usort function has very powerful custom sorting capabilities. Different sorting rules can be implemented by simply defining a callback function. But it should be noted that the callback function needs to return an integer value to ensure that the function can work properly.

The above is the detailed content of How to use the usort function to custom sort an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles