Thursday, June 4, 2009

Hi
i am newbie to PHP and MySQL.
Recently i want to sort array elements. i sort array elements using classic for loop. but i think there going to more efficient ways of doing it. i heard about sort(),asort()and ksort(). So what’s the difference between sort(), asort() and ksort?
if explained with examples that would be appriciated.

regards,
saurabh

1 comment:

  1. Hey saurabh..
    This mite solve ur probs..

    1) sort()
    This function sorts an array. Elements will be arranged
    from lowest to highest when this function has completed.



    $fruits = array("lemon", "orange", "banana", "apple");
    sort($fruits);
    foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
    }


    ----------------------------OUTPUT---------------------
    fruits[0] = apple
    fruits[1] = banana
    fruits[2] = lemon
    fruits[3] = orange
    -------------------------------------------------------

    2) 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.


    $fruits = array("d" => "lemon", "a" => "orange", "b" =>
    "banana", "c" => "apple");
    asort($fruits);
    foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
    }


    --------------------OUTPUT------------------------
    c = apple
    b = banana
    d = lemon
    a = orange
    --------------------------------------------------

    3) ksort()
    Sorts an array by key, maintaining key to data
    correlations. This is useful mainly for associative arrays.


    $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana",
    "c"=>"apple");
    ksort($fruits);
    foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
    }


    --------------------OUTPUT----------------------------
    a = orange
    b = banana
    c = apple
    d = lemon
    ------------------------------------------------------

    If any more query about this comment.. let me know..

    ReplyDelete