Page 1 of 1

SOLVED: ksort

Posted: Wed Feb 22, 2012 11:41 am
by AdrianK_IT
I'm new to PHP!
I am writing a script to sort new entries pasted into a hosts file into ascending IPv4 address order. The script works fine, and (to my surprise) eliminates any duplicate entries.
I say 'to my surprise' because I haven't (yet) written any explicit code to eliminate duplicate entries; the ksort function (operating on the decimal numerical value of the IP addresses as keys) seems to take care of this automatically.
Should I have expected this? Or am I just lucky?! Always nervous of the unexpected, even if it's good news!
With thanks.

Re: ksort

Posted: Wed Feb 22, 2012 4:49 pm
by xtiano77
If is always difficult to answer hypothetical questions. That said, you should post the piece of code in questions so the rest of us along with the experts can take a look at it and be able to give you a better more intelligent answer. Right now, without looking at your code we would guessing.

Re: ksort

Posted: Wed Feb 22, 2012 8:30 pm
by RobertGonzalez
If you are building an array of values and you use a duplicate array key you are in effect overwriting any previous data stored in that array member. All ksort() is going to do is order your array for you by key. Its not going to do anything else to your array. So if you were to inspect your array prior to running it through ksort() you'd see that you have unique entries simply because new entries with the same key value overwrite previous entries with the same key value.

SOLVED Re: ksort

Posted: Thu Feb 23, 2012 9:37 am
by AdrianK_IT
Thanks for your help on this.
I realise now that the elimination of duplicate entries (overwriting) is being carried out by an array_combine function in my code, operating as I would expect.
I understand the reasons for it (so I'm not complaining), but the requirement for new members to complete a captcha for every post (even previews) makes posting code impractical for me. I have poor eyesight; captchas are a nightmare. Yet, as an inexperienced coder, I can't risk posting code without previewing how it appears. I could waste a lot of other people's time if errors creep in.

Re: SOLVED: ksort

Posted: Thu Feb 23, 2012 11:08 am
by AdrianK_IT
PS I have posted the code at http://ethinks.org/ksort.htm