Sort(); changes key numbers of array

Hello!
I have a question about using function sort();
I set the initial key of array to be 1 (instead of default 0). Everything goes OK until I sort the array. After sorting the array initial key value sets itself back to zero.
Here is the example:
<?php
$var = array(1 => "Good", "Better", "The Best");
foreach ($var as $index => $value)
     echo $index." - ".$value."<br />";
sort($var);
foreach ($var as $index => $value)
     echo "<br />".$index." - ".$value;
?>
How to avoid the change of the initial array key?
The output should be:
1 - Better
2 - Good
3 - The Best

DissidentPJ wrote:
I have a question about using function sort();
I set the initial key of array to be 1 (instead of default 0). Everything goes OK until I sort the array. After sorting the array initial key value sets itself back to zero.
Yes, of course, it will. If you read the PHP manual page for sort(), it says quite clearly "This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys."
PHP has a large number of sort functions to handle a variety of requirements. However, what you want to do is to reorder the values AND renumber the keys. The simple way to do it is to use sort(), which puts the values in the right order starting at 0. Just add 1 to the key when you use it.

Similar Messages

  • Arrays.sort() issue when Numbers are a string!

    Hey guys -- here is my problem.
    I am working on a TOP TEN SCORES mechanism for a trivia game. I have read in the score and the players name from a file. SO I have 2 different arrays topScores[] and topNames[] ---
    Now if someone plays the game and has a higher score than the lowest score, they get to put their score and name in the file and replace the low score.
    HOWEVER -- I do not know how to sort topSCORES[] and then make whatever sorted changes apply also to the topNAMES[] array.
    SO I thought - HEY I will concatenate the topScores and topNames into a single String array. And then SORT! This sounded like a great idea until I realized that the following will happen:
    100 tvance (first one)
    1000 dvance (second score)
    250 danderson (third score) !!!
    See my problem? When I sort this way - it is sorting alphabetically so it will put a 1000 score before a 200-900 score! ---
    **I hope I explained this adequately -- can someone help? Is there a way to sort the topScores array and have it also change the order of the topNames array as well?

    Create a new class - HighScore, which has a highScore and a name?Yup. This technique even has a name: object-oriented programming!
    Demo:
    import java.util.*;
    public final class HighScore implements Comparable<HighScore> {
        private final int score;
        private final String name;
        public HighScore(int score, String name) {
            if (name == null)
                throw new NullPointerException();
            this.score = score;
            this.name = name;
        public int getScore() {
            return score;
        public String getName() {
            return name;
        public int compareTo(HighScore that) {
            if (this.score < that.score)
                return -1;
            else if (this.score > that.score)
                return +1;
            else
                return this.name.compareTo(that.name);
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            else if (obj instanceof HighScore) {
                HighScore that = (HighScore) obj;
                return this.score == that.score && this.name == that.name;
            } else
                return false;
        public int hashCode() {
            return score ^ name.hashCode();
        public String toString() {
            return score + " " + name;
        //demo
        public static void main(String[] args) {
            HighScore[] top = {
                new HighScore(250, "danderson"),
                new HighScore(1000, "dvance"),
                new HighScore(100, "dvance")
            Arrays.sort(top);
            for(int i=0; i<top.length; ++i) {
                System.out.println(top);
    If you are using an older version of Java (1.4 or earlier), the generics won't be
    recognized. In that case the class definition would begin:
    public final class HighScore implements Comparable {And the compareTo method would begin:
    public int compareTo(Object obj) {
        HighScore that = (HighScore) obj;Good luck!

  • TS2549 iphoto 11 (9.2.3), cannot sort iphoto in events. Text changes to numbers?

    I use 10.6.8 MacBook mid 2007 iphoto 11 (9.2.3),
    Cannot sort iphoto in event, when almost finished it changes to numbers.
    I have done it for three times.
    It does not work.
    Faces will not show up correctly either, but that is  not so important.
    Please help

    Please explain
    Cannot sort iphoto in event, when almost finished it changes to numbers.
    How are you "sorting photos in events"?
    Typically you use albums for organization - like sorting
    LN

  • I'm trying to change my program to arrays so I can sort it

    My program asks for 13 scores
    oneString = JOptionPane.showInputDialog("Choose a test score 0-100");
              one = Integer.parseInt(oneString);
    and so on till 13, then at the bottom I want to sort the 13 numbers so I can just take the highest and lowest to find the range. I have to have this in arrays so I can sort it using arrays.sort () method. I don't know where to make the numbers into arrays or how to start the #'s off as arrays. Could anyone tell me how?

    I want to sort
    the 13 numbers so I can just take the highest and
    lowest to find the range.Sorting generally is a bad idea in this case. There's a very simple and straightforward algoritm available for finding the extreme values in a list of numbers. This is how to find the max value. Finding min is similar.
    int max = list[0]; // first number is max so far
    for (int i=1; i<list.length; i++) // all remaining numbers in list
       if (max < list) // current max is smaller than other number
    max = list[i]: // so assign new max

  • Event Structure's value change, not detecting changes when tabbing thru array of clusters

    Hi!  I have an array of clusters (int, int, string, int) control, and want to detecting changes made to the it.  I used the Event Structure's value change case on the array, it works excellent except that it'll only detect the changes when you click out of the element or press the enter key (the one by the numbers, not carriage return).  I want it to detect the changes when I tab thru the cluster or array too, but I can't figure it out... Does anyone have any ideas?
    Thanks!

    mfitzsimons wrote:
    altenbach
    Tried Value Change with my example done in 7.1 and it doesn't trgger an event.  That is why I suggested Mouse Down.
    Curious. I did a few minor edits in 8.0 before saving as 7.1, but the simple value change event got triggered just fine when the value vas terminated with a tab in 7.1. Every time.  Strange....
    Are you on 7.1 or 7.1.1? Maybe there's a difference (I am using 7.1.1).
    LabVIEW Champion . Do more with less code and in less time .

  • How to change the numbers of items in a ring control in run time ?

    Hi !
    I would like change the numbers of items in a ring control in run time, but I can´t.
    Thanks.

    Hello blaze,
    did you try the "Strings And Values []" property of the ring?
    LabView7.1 help says:
    Array of clusters containing the strings from which you can select in the ring control
    and the numeric values for each item. Use the Strings [] property if you do not need to
    assign specific numeric values to each item.
    Best regards,
    GerdW
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • How can I use the defaults command to edit a sub key in an array of plist?

    For example, how could I edit the Name key in the array?
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    <key>Test</key>
    <array>
    <dict>
    <key>IPAddress</key>
    <string>xxxx</string>
    <key>Name</key>
    <string>yyyy</string>
    </dict>
    </array>
    </dict>
    </plist>

    I realize you are asking specifically about 'defaults', but as they concede in 'man defaults', it may not be the best tool for editing properties in "complex" structures, such as those buried in dicts within arrays, etc.
    As an alternative, it looks like in 10.5, '/usr/libexec/PlistBuddy' is now a part of the standard install - 'PlistBuddy' may be more useful for this sort of task.
    For example:<pre>
    /usr/libexec/PlistBuddy -c "set Test:0:Name zzzz" /path/to/file.plist</pre>

  • Sorting a Key Figure by default in a query

    Hi,
    I'm trying to set up a query with a key figure that is sorted in descending order by default everytime.  I tried creating the following condition:
    Key Figure - Sales Volume
    Operator - Top %
    Values - 100
    This sorts the key figure in descending order to a point.  When I add a characteristic to the report (for example, sold to), the sorting is no longer active.  I would like this key figure to remain sorted in descending order regardless of the any manipulation to the report.  But, I'd still like the user to have the ability to change the sorting if they want to sort by another key figure (ascending or descending)
    I'm using the BI 7.0 Query Designer.
    Thanks!!

    Check this:
    Sort Key Figures and Maximum query result
    Organising key figures in BEx Query Designer
    ordering display in a KF
    Hope it helps..

  • So in the last few days I've noticed that pressing my volume change keys actually isn't changing the volume on my macbook pro at all. When I press the volume up or down keys, it makes the recognisable pop sound but stays at the same volume while the squar

    So in the last few days I’ve noticed that pressing my volume change keys actually isn’t changing the volume on my macbook pro at all. When I press the volume up or down keys, it makes the recognisable pop sound but stays at the same volume while the squares go up or down. I mute it but my computer still makes sound. It’s the same with the volume control up the top of the screen, too. I slide it up and down and it doesn’t change the volume at all. The only way I can change the volume is with my speakers or the program I’m in (iTunes, VLC etc). I restarted and it seems to be okay then I go to change it a couple minutes later and it’s back to not working again.
    I’ve checked my settings- the “use all F1, F2, etc. keys as standard fuction keys” is not switched on, and I have tried a suggestion of moving the com.apple.systempreferences.plist file out of the library and onto the desktop and restarting and neither of those seem to make any difference whatsoever. I’ve tried to find online forums but the only suggestions I found were those two and they didn’t work.
    I’m just annoyed because I usually have the worst luck with technology but my macbook had been going strong and I got it because of the apparent lack of things that could go wrong, but of course even if there is one thing that could go wrong it will happen to me.
    Please help!

    You migh give resetting your NVRAM a try:
    http://support.apple.com/kb/ht1379

  • How to compare consecutive groups of numbers in arrays

    Hi
    I require to place the solution into a 1D array.
    I need to compare two arrays and save the same numbers that are in both arrays but also save groups of numbers that may be in only one of the two arrays being compared.
    In the example l have not been able to place all consecutive groups of numbers 8,9,10,11,12 into a 1D array.
    In the example l need to filter out the zeros and the number four.
    The numbers in both arrays are always in descending order however may not be in the order of index number of array. That is 15 = 15 index number
    A consecutive group of numbers in this example is a group that increase by a value of 1. E.g.. 8,9,0,22,23,24 are two consecutive groups of numbers.
    Thank  you
    Solved!
    Go to Solution.
    Attachments:
    Compare numbers and consecutive numbers in arrays.vi ‏17 KB

    Hi Lynn
    I did have a look at the consecutive array solution. I have looked and looked l thought l knew how it worked but after a number of separate evaluations with other code l have failed. I am just glad it works. With the consecutive array solution l tried today my own code but l lost either the first number of the last number of a consecutive group of numbers.
    I may have confused you but in doing so you have provided a real different view which l am very grateful. You have viewed the consecutive number problem as just a single 1D array problem. By doing this you have opened my eyes to another way to do the job and a way to handle this type of data. However l am also comparing two arrays. For example l have to pick up say two equal values in two columns that the consecutive array does not detect and then correctly locate a value in the final array if the value is not in the final array.
    What l have not told you is also l have to be able to identify groups of numbers in two 1D arrays. E.g... Array 1 has 1,2,9,10 next array has 9,10 the final array ends up 9,10 when l would like 0,9,10. When viewing numbers by rows later on l can then detect with a array length vi the length of the 1,2 groups of numbers over a large number of columns. If 9,10 jumps to the front it becomes a wrong length. This is actually my main problem which has caused me a large amount of extra programming. I have gone back to basics to see what l can do differently and you have provided the first clue with the consecutive array. I placed it in my main program today and it filtered a lot variable data which l could not remove without losing real data. The main data lost in your solution was the say 17 number in two columns which in an image is a horizontal line. I know what l have just provided you in this paragraph is all new information but it provides a background as to what l am up to. I am getting pixel data from a 2D array and comparing +1 index 1D array with a normal array. This way l can view the data of the next column to see if there is a pattern. I am actually trying to program an array as how humans view objects in images.
    I will have another go at integrating your solution next week
    Regards
    Michael

  • Changing content in an array

    can someone help me with changing content in an array. The index will be specified by the user entering the index number.
    eg
    Enter the item number to Change
    1
    Then I need to replace the data in this index with new data.
    I am very new to java so I am sorry if this seems like a stupid questions. Your help is much appreciated.
    thanks

    public void modifyIt(String[] myArray){
      System.out.println("Which index?");
        int index = readResponse() //read in response somehow
      System.out.println("Whats the new data?");
      String data = readResponse() // read in response
      myArray[index] = data;
    }

  • Changing/Adding Numbers to the Network/Dial-Up Connection Thing-a-ma-bob...

    I would like to do this:
    *Put these numbers in Network>TCP/IP>DNS Servers...*
    208.67.222.222
    208.67.220.220
    But I am scared to death to try. I get connected without a hitch now, and I do NOT want to disturb that!!! I don't know what I am doing with this, but if it will improve the speed and stability of my dial-up connection so I can successfully download and install my updates, I will risk it.
    How much chance do I have of messing my connect-ability up altogether?
    And how do I go about doing it properly?
    Cyan

    99.999999% safe and easy to undo, but to make it even nearer 100%...
    In the Network Pref Pane, choose the Location drop down, choose Edit Locations, then choose Duplicate... now you have one you can paste those numbers into, and just switch Locations back if need be without changing any numbers.
    It's safe though anyway really.:-)

  • Just setting up iCloud on my iMac, my problem is when trying to sign out/off from iCloud it comes up with a verification code that is being sent to my land line, I'd changed the numbers in my Apple ID and they show as changed but the land line number stil

    Just setting up iCloud on my iMac 10.9.2, my problem is when trying to sign out/off from iCloud it comes up with a verification code that is being sent to my land line, I'd changed the numbers in my Apple ID and they show as changed but the land line number still shows as number that the verification code is being sent, I prompt "Don't have access to this phone" and that's no help at all.  The only way I can sign out /off from iCloud is to uncheck everything that I wanted to keep in the cloud????
    Thanks in advance for any help.

    Skip the iCloud sign in for now.
    Once you reach the home page, go to settings and sign out of FaceTime and Messages.  This should also sign you out of iCloud.
    Go to iCloud in settings and sign in with the correct Apple ID.
    If that does not work
    Skip the iCloud sign in
    Go to Apple ID.apple.com and sign in
    Change your Apple ID to the old one
    Delete iCloud account on your device with the old Apple ID and the same password.
    Go back to the website, change your Apple ID back to the current one. You will receive an email to verify the account. Verify first.
    Sign into iCloud on your device with the correct Apple ID and password

  • Is there somebody out there to shed some light on this? Change keys, tempo in Soundtrack Pro greyed out?

    From the amount of posted unanswered questions like mine one should be able to see that there are more than a few people confused about the greyed out "Change keys, tempo in Soundtrack Pro" (and for that matter in Apple Loops Utility, Logic, GarageBand)! What does it take to help out the less adept budding beginners? Please don't post read the manual or search for... we all know you can spend days with no results. There is nothing better than a friendly person (wizard) who knows and has done it all, giving clear step by step instructions. Please lay it out for us lesser brains. Thank you so much for your time and patience.

    rs = stmt.executeQuery("SELECT gender FROM gymuser WHERE Username= 'userName' ");
    in this line i think there is some error put it like this
    rs = stmt.executeQuery("SELECT gender FROM gymuser WHERE Username= '"+userName+"' ");
    Try to put some SOPs in between, so that u can check in logs(if using tomcat)where u r making mistake.

  • Error while using sort by key lexicographically

    Hi,
    while sorting records lexicographically using sort by key function, i got the below error.
    RuntimeException in Message-Mapping transformation: Runtime exception during processing target field mapping /ns0:MT_WorkOrderData/MessagePayload/Record/CAUFVD_KTEXT. The message is: Exception:[java.lang.IllegalArgumentException: Cannot parse apple to BigDecimal. ] in class com.sap.aii.mappingtool.flib3.NodeFunctions method sortByKey[com.sap.aii.mappingtool.flib3.Plainer@264b264b, com.sap.aii.mappingtool.flib3.Plainer@42674267]
    i need to sort the input records from a file based on a field which is of type string.
    Thanks in advance,
    Jhansi.

    Jhansi,
    Did u referred the thread:Re: Problem in sorting the records
    Best regards,
    raj.

Maybe you are looking for

  • Best practice for saving and recalling objects from disk?

    I've been using the OOP features of LabVIEW for various projects lately and one thing that I struggle with is a clean method to save and recall objects. Most of my design schemes have consisted of a commanding objects which holds a collection of work

  • BI 7.0 integration with EP

    Dears, I have recently installed BI IDES server on Windows server and Oracle 10g database. Now I want to integrate it with portal,For it when I am executing report RSPOR_SETUP,It giving output   BI1_certificate.crt is not existing.   Existence of BW

  • X-path query to get all versions of  a node at a given path in JSP

    hi need a xpath query so that i can list all the versions of a selected node which can be used for restoring the version to that particular one??

  • Best procedure to downgrade a SQL Server 2012 SP2 installation from Enterprise edition to Standard edition

    Hi, following a purpose change for a database server, I need to downgrade the SQL Server 2012 SP 2 installation from Enterprise to Standard edition. Does it exist the best procedure to do it in a secure manner with a low impact? Many thanks

  • Variable Handling, use Session?

    Currently a menu link 'user admin' takes you to list of users which are subscribed to topics. The clients wants multiple menu links, e.g. 'user admin - topic', so that when they go to the user admin they are only dealing with users subscribed to a sp