List functions available to sort a php array? Explain with an Example.

PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we’ll explore some of these functions most commonly used for sorting arrays.


sort(array &$array, int $flags = SORT_REGULAR): bool

PHP array sort function examples

1) Using the PHP sort() function to sort an array of numbers

This example uses the PHP sort() function to sort an array of three numbers:


    $numbers = [2, 1, 3];

    print_r ($numbers);


    [0] => 1
    [1] => 2
    [2] => 3

2) Using the PHP sort() function to sort an array of strings

This example uses the sort() function to sort an array of strings alphabetically:


    $names = ['Bob', 'John', 'Alice'];
    sort($names, SORT_STRING);



    [0] => Alice
    [1] => Bob
    [2] => John

3) Using the PHP sort() function to sort an array of strings case-insensitively


    $fruits = ['apple', 'orange', 'banana', 'pink' ];



4) Using the PHP sort() function to sort an array of strings using “natural ordering”

To sort an array of strings in the “natural ordering”, you combine the SORT_STRING  SORT_NATURAL flags.



    $ranks = ['A-1', 'A-12', 'A-2',  'A-11'];
    sort($ranks, SORT_STRING | SORT_NATURAL);



Related Posts

Associative Array in PHP?

An associative array is a simple and very important array of PHP. This array is also used the most, it is very easy to understand this array,…

How to work in functions PHP?

If there is any task in your program which you train to execute repeatedly then instead of writing the code for that task at a different place…

For Loofs in PHP

In for-loop initialization, condition and increment happen on the same line. The loop keeps on repeating as long as the condition is true. When the for loop…

If Else Conditionals in Php?

If Else statement is the most important feature of any programming language, PHP is used to run any Code Of Block according to If Else conditions. This…

What are operators in PHP? PHP – Operator Types

Operators are used to developing data. In Programming Languages, Operators are taken from Mathematics and Operator Programmers work with Data. An operator is a chain of symbols…

String Functions in PHP?

When many characters are written together in sequence, they form a string. For example, India is a string. It is made up of i, n, d, i,…

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x