Aditya Thakur
Aditya Thakur

Reputation: 125

How to implement the functionality of the asort function without using the keyword asort()?

This is my simple code.

    <?php
     $num=array('a'=>5, 'b'=>3, 'c'=>1);
    ?>

How to sort this array while maintaining index association witout using asort()?

Upvotes: 0

Views: 86

Answers (1)

Aman Kumar
Aman Kumar

Reputation: 4557

Check Custom_asort() Example

   <?php

/* Custom asort function */
function custom_asort($num)
{
    $return = $numbers = array();   // empty array 
    foreach($num as $key => $val)
    {
        $numbers[] = $val ;
    }
    sort($numbers);  // sort number 
    $arrlength = count($numbers);   // count array lenght 
    for($x = 0; $x < $arrlength; $x++) {
        $key = array_search($numbers[$x], $num);      // array_search apply for search key according to index 
        $return[$key] = $numbers[$x]; 
    }
    echo "<pre>";
    print_r($return);  // print function output 
}
$num=array('a'=>5, 'b'=>3, 'c'=>1, 'd'=>2);   // array 
custom_asort($num);  // calling function 
?>

Upvotes: 1

Related Questions