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

Posted by

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOps School!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

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:-

Leave a Reply

Your email address will not be published. Required fields are marked *

0
Would love your thoughts, please comment.x
()
x