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

Posted by

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.

Syntax:-

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:

<?php

    $numbers = [2, 1, 3];
    sort($numbers);

    print_r ($numbers);
    
?>

Output:-

Array       
(
    [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:

<?php

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

    print_r($names);
    
?>

Output:-

Array
(
    [0] => Alice
    [1] => Bob
    [2] => John
)

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

<?php

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

    print_r($fruits);
    
?>

Output:-

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.

Example:-

<?php

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

    print_r($ranks);
    
?>

Output:-

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