Tuesday, April 23, 2013


<?php

    $fruits = array("lemon", "orange", "banana", "apple");
    echo "The Original Array is:<br>";
    foreach ($fruits as $key => $val) 
    {
        echo "fruits[" . $key . "] = " . $val . "<br>";
    }

    echo "<br>The Array After sort() is:<br>";
    sort($fruits);
    /*
        sort()
        This function sorts an array. Elements will be arranged 
        from lowest to highest when this function has completed.

    */
    foreach ($fruits as $key => $val) 
    {
        echo "fruits[" . $key . "] = " . $val . "<br>";
    }
    /*
        ----------------------------
OUTPUT---------------------
        fruits[0] = apple
        fruits[1] = banana
        fruits[2] = lemon
        fruits[3] = orange
        -------------------------------------------------------
    */

    /*
        asort()
        This function sorts an array such that array indices
        maintain their correlation with the array elements they are
        associated with. This is used mainly when sorting
        associative arrays where the actual element order is
        significant.
    */
    echo "<br>The Array After asort() is:<br>";
    $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
    asort($fruits);
    foreach ($fruits as $key => $val)
    {
        echo "$key = $val<br>";
    }
    /*
        --------------------OUTPUT------------------------
        c = apple
        b = banana
        d = lemon
        a = orange
        --------------------------------------------------

    */
   
    /*
        ksort()
    Sorts an array by key, maintaining key to data
    correlations. This is useful mainly for associative arrays.
    */
    echo "<br>The Array After ksort() is:<br>";
    $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
    ksort($fruits);
    foreach ($fruits as $key => $val)
    {
        echo "$key = $val<br>";
    }
    /*
    --------------------OUTPUT----------------------------
    a = orange
    b = banana
    c = apple
    d = lemon
    ------------------------------------------------------
    */

    echo "<br><br><br><br>Revese Sort";
    $input = array ("Pinaple", "Orange", "Banana", "Mango", "Apple","Strawberry");
    $input1=$input;
    $input2=$input;
    $input3=$input;
    echo "<br>-----Original Array---------<br>";
    while (list ($key, $val) = each ($input))
    {
        echo "$key -> $val <br>";
    }
    sort($input1);
    echo "<br>-----After sort---------<br>";
    while (list ($key, $val) = each ($input1))
    {
        echo "$key -> $val <br>";
    }

    rsort($input2);
    echo "<br>-----After rsort---------<br>";
    while (list ($key, $val) = each ($input2))
    {
        echo "$key -> $val <br>";
    }
    arsort($input3);
    echo "<br>-----After rsort---------<br>";
    while (list ($key, $val) = each ($input3))
    {
        echo "$key -> $val <br>";
    }
?>

0 comments:

Post a Comment