A Simple Array Sort in PHP

Discussion in 'Web Design and Development' started by covertsurfer, May 23, 2008.

  1. covertsurfer macrumors 6502a

    Joined:
    Jan 18, 2007
    #1
    I have an array 1,10,2,3,4,5,6,7,8,9

    I want to sort it so I can return 1,2,3,4,5,6,7,8,9,10

    I have tried the PHP function sort but it returns it in the original format.

    Please help
     
  2. SilentPanda Moderator emeritus

    SilentPanda

    Joined:
    Oct 8, 2002
    Location:
    The Bamboo Forest
    #2
    My guess (I'm no PHP guru) is that it is sorting it properly.

    1, 10, 2, 3, 4, 5, 6, 7, 8, 9 is already sorted... just not numerically.

    Look into the PHP sort flags to have it sort numerically instead of "regular".

    Basically it is sorting the 10 after the 1 since they both start with "1". If you look at the array with alpha replacements you would get something like:

    B, BA, C, D, E, F, G, H, I, J
     
  3. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #3
    Yup, like SilentPanda said,

    PHP:
    $array = array(1,10,2,3,4,5,6,7,8,9);
    sort($arraySORT_NUMERIC);
    Ref: http://www.php.net/sort
     
  4. SilentPanda Moderator emeritus

    SilentPanda

    Joined:
    Oct 8, 2002
    Location:
    The Bamboo Forest
    #4
    I don't think your code above works. Again I don't know PHP well but I do code. The API says sort returns a boolean. It looks like it sorts the array in place. So there is no need to send the value to $newarray since it actually sorts $array.

    I could be wrong though.

    Edit: Ah never mind, looks like you changed your code... :)
     
  5. Eraserhead macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #5
    That or using natsort()
     
  6. SilentPanda Moderator emeritus

    SilentPanda

    Joined:
    Oct 8, 2002
    Location:
    The Bamboo Forest
    #6
    natsort doesn't change the keys though. Although maybe the OP doesn't need them changed. natsort would confuse me when I tried looping through the array I think... unless I was using it more like a key/value map.
     

Share This Page