Learn How To Use Sort Array Function With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 24-09-2020

sort arrays in ascending order. Sort Array Elements in Ascending Alphabetical Order.

PHP Sort Functions For Arrays with example

First Need to Create Arrays

1.Create Array:

$Fruits = array("Cherries", "Mango", "Grape","Blueberry");

2.Sort()
sort arrays in ascending order.
Sort Array Elements in Ascending Alphabetical Order.


Example(1)
<?php
$Fruits = array("Cherries", "Mango", "Grape","Blueberry");
sort($Fruits);
$arraylength = count($Fruits);
for($x = 0; $x < $arraylength; $x++) {
    echo $Fruits[$x];
}
?>

Sort Array Elements in Ascending Numerical Order.

Example(2)
<?php
$numbers = array(10, 50, 4, 2, 100);
sort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
    echo $numbers[$x];
}
?>

Complete Code of Sort() Array Elements:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP Sorting Arrays</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>PHP Sorting Arrays</h1>
    </div>
    <h2>Sort Array Elements in Ascending Order - Sort()</h2>
    <h2>1.Sort Array Elements in Ascending Alphabetical Order</h2>
    <div class="well">
        <?php
        $Fruits = array("Cherries", "Mango", "Grape","Blueberry");
        sort($Fruits);
        $arraylength = count($Fruits);
        for($x = 0; $x < $arraylength; $x++) {
            echo "<h4>".$Fruits[$x]."</h4>";
        }
        ?>
    </div>
    <br>
    <h2>2.Sort Array Elements in Ascending Numerical  Order</h2>
    <div class="well">
        <?php
        $numbers = array(10, 50, 4, 2, 100);
        sort($numbers);

        $arrlength = count($numbers);
        for($x = 0; $x < $arrlength; $x++) {
            echo "<h4>".$numbers[$x]."</h4>";
        }
        ?>
    </div>
</div>
</body>
</html>

Related Post