How to order an array from largest to smallest and then print them

Discussion in 'PHP' started by Ipodman79, Feb 14, 2014.

  1. #1
    How do I order an array from largest to smallest and then print the answers.

    
    $number = array(2, 3, 4, 3);
    
    PHP:
    How do I do this?
     
    Ipodman79, Feb 14, 2014 IP
  2. HolyRoller

    HolyRoller Well-Known Member

    Messages:
    552
    Likes Received:
    27
    Best Answers:
    1
    Trophy Points:
    150
    #2
    rsort($number)
    foreach ($number as $val) {
         echo "$val\n";
    }
    Code (markup):
     
    HolyRoller, Feb 14, 2014 IP
  3. Ipodman79

    Ipodman79 Greenhorn

    Messages:
    43
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    6
    #3
    Do you know how to add the number the number is in an array, so if I had,

    
    $number = array(2, 3, 4, 3); // 2 would be $number[0], 3 would be $number[1], etc
    
    PHP:
    how i would add 0 to 2, 1 to 3, etc?
     
    Ipodman79, Feb 14, 2014 IP
  4. HolyRoller

    HolyRoller Well-Known Member

    Messages:
    552
    Likes Received:
    27
    Best Answers:
    1
    Trophy Points:
    150
    #4
    If you need to keep the key the same, you need to use arsort($number).

    To add $number[0] to $number[2] you just do $number[0]+$number[2] but what are you doing with the result? just displaying it or putting into another array or something else?
     
    HolyRoller, Feb 14, 2014 IP
  5. Ipodman79

    Ipodman79 Greenhorn

    Messages:
    43
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    6
    #5
    What I want to do is add 2 to $number[2]. However I want to be able to do this to as many number as there are in the array. So add the number, 4 to $number[3]. Does that make sense?
     
    Ipodman79, Feb 14, 2014 IP
  6. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #6
    For each number in the array, you want to add the count to the existing number:
    
    // existing array
    array(1,2,3,4)
    //new array
    array(1,3,5,7)
    
    PHP:
    if so, just do something like
    
    $array = array(1,2,3,4,5);
    $newarray = array();
    
    for ($i = 0; $i < count($array); $i++) {
       $newarray[] = $array[$i] + $i;
    }
    
    print_r($newarray);
    
    PHP:
     
    PoPSiCLe, Feb 14, 2014 IP
  7. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #7
    Another way of what PoPSiCLe came up with:

    
    $ar = array(1, 2, 3, 4, 5);
    $ar2 = array_map(function($a, $b){ return $a+$b;}, $ar, range(0, count($ar)-1));
    print_r($ar2);
    
    PHP:
     
    ThePHPMaster, Feb 14, 2014 IP