Monday 5 April 2021

Php: sort: Sort the elements of array in ascending order

‘sort’ function return the elements in ascending order (in place, affect the original array).

 

Syntax

sort($array_name);

 

Example

sort($arr);

 

Find the below working example.

 

array_sort_demo.php

#!/usr/bin/php

<?php

    $arr = array(22, 31, -5, 77, -98, 18);
    
    echo "Original array : \n";
    print_r($arr);

    sort($arr);

    echo "Sorted array in ascending order : \n";
    print_r($arr);
    
?>

 

Output

$./array_sort_demo.php 

Original array : 
Array
(
    [0] => 22
    [1] => 31
    [2] => -5
    [3] => 77
    [4] => -98
    [5] => 18
)
Sorted array in ascending order : 
Array
(
    [0] => -98
    [1] => -5
    [2] => 18
    [3] => 22
    [4] => 31
    [5] => 77
)

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment